当前位置: 首页>>代码示例>>Golang>>正文


Golang net.Pipe函数代码示例

本文整理汇总了Golang中net.Pipe函数的典型用法代码示例。如果您正苦于以下问题:Golang Pipe函数的具体用法?Golang Pipe怎么用?Golang Pipe使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Pipe函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestClientMassError_json

func TestClientMassError_json(t *testing.T) {
	cli, srv := net.Pipe()
	go ServeConn(srv)
	client := NewClient(cli)
	defer client.Close()

	for i := len(svcMsg); i < cap(svcMsg); i++ {
		svcMsg <- ""
	}
	defer func() {
		for len(svcMsg) > 0 {
			<-svcMsg
		}
	}()

	wanterr1 := NewError(-32603, "json: cannot unmarshal number into Go value of type string")
	wanterr2 := NewError(-32603, "some other Call failed to unmarshal Reply")

	call2 := client.Go("Svc.Msg", []string{"test"}, nil, nil)
	var badreply string
	err1 := client.Call("Svc.Sum", [2]int{}, &badreply)
	if err1 == nil || !reflect.DeepEqual(ServerError(err1), wanterr1) {
		t.Errorf("%serr1 = %v, wanterr1 = %v", caller(), err1, wanterr1)
	}
	<-call2.Done
	err2 := call2.Error
	if err2 == nil || !reflect.DeepEqual(ServerError(err2), wanterr2) {
		t.Errorf("%serr2 = %v, wanterr2 = %v", caller(), err2, wanterr2)
	}
}
开发者ID:plumbum,项目名称:rpc-codec,代码行数:30,代码来源:protocol_test.go

示例2: TestProxy

func TestProxy(t *testing.T) {
	apipe, b1pipe := net.Pipe()
	b2pipe, cpipe := net.Pipe()

	// A
	achan := make(chan chan string)
	axport := New(apipe, nil)
	axport.FromChan(achan)

	// B
	bchan := make(chan chan string)
	b1xport := New(b1pipe, nil)
	b2xport := New(b2pipe, nil)
	b1xport.ToChan(bchan)
	b2xport.FromChan(bchan)

	// C
	cchan := make(chan chan string)
	cxport := New(cpipe, nil)
	cxport.ToChan(cchan)

	victim := make(chan string)
	achan <- victim
	proxied := <-cchan

	want := "test"
	proxied <- want
	if got := <-victim; got != want {
		t.Errorf("got %q through proxy, want %q", got, want)
	}
}
开发者ID:Nightgunner5,项目名称:fatchan,代码行数:31,代码来源:fatchan_test.go

示例3: TestNextError

func TestNextError(t *testing.T) {
	t.Parallel()

	var want, got error
	pipe1, pipe2 := net.Pipe()
	tcpTsp := NewTCP(pipe1, stream.Receiving, nil, true)

	// Error from xml.Decoder should be returned
	go func() {
		_, err := pipe2.Write([]byte("</whoops>"))
		if err != nil {
			t.Errorf("An unexpected error occurred: %s", err)
		}
	}()
	_, got = tcpTsp.Next()
	if _, ok := got.(*xml.SyntaxError); !ok {
		t.Error("Error from xml.Decoder should be returned.")
		t.Errorf("Wanted xml.SyntaxError, Got:(%T)%s", got, got)
	}

	pipe1, pipe2 = net.Pipe()
	tcpTsp = NewTCP(pipe1, stream.Receiving, nil, true)
	go func() {
		_, err := pipe2.Write([]byte("<foo><bar></whoops>"))
		if err != nil {
			t.Errorf("An unexpected error occurred: %s", err)
		}
	}()
	_, got = tcpTsp.Next()
	if _, ok := got.(*xml.SyntaxError); !ok {
		t.Error("Error from xml.Decoder should be returned.")
		t.Errorf("Wanted xml.SyntaxError, Got:(%T)%s", got, got)
	}

	// Receiving an xml end element should return stream.ErrStreamClosed
	pipe1, pipe2 = net.Pipe()
	tcpTsp = NewTCP(pipe1, stream.Receiving, nil, true)
	go func() {
		_, err := pipe2.Write(stream.Header{}.WriteBytes())
		if err != nil {
			t.Errorf("An unexpected error occurred: %s", err)
		}
		_, err = pipe2.Write([]byte("</stream:stream>"))
		if err != nil {
			t.Errorf("An unexpected error occurred: %s", err)
		}
	}()
	want = stream.ErrStreamClosed
	_, err := tcpTsp.Next()
	if err != nil {
		t.Errorf("Unexpected error: %s", err)
	}
	_, got = tcpTsp.Next()
	if !reflect.DeepEqual(want, got) {
		t.Error("Receiving an xml end element should return stream.ErrStreamClosed.")
		t.Errorf("\nWant:%s\nGot :%s", got, got)
	}
}
开发者ID:skriptble,项目名称:nine,代码行数:58,代码来源:tcp_test.go

示例4: TestServer

func TestServer(t *testing.T) {
	errChan := make(chan error, 1)
	s := NewServer(errChan)

	// Subscribe to listen a channel
	var ch uint32 = 37
	lis1, lis2 := net.Pipe()
	go s.Handle(lis2)

	reqData, err := api.WriteRequest(&api.Request{Channel: ch, Type: api.Listen})
	if err != nil {
		t.Fatal("WriteRequest: ", err)
	}
	if _, err := lis1.Write(reqData); err != nil {
		t.Fatal("Write(reqData): ", err)
	}

	// Send payload to the channel
	send1, send2 := net.Pipe()
	go s.Handle(send2)
	payload := []byte("foo")
	if reqData, err = api.WriteRequest(&api.Request{Channel: ch, Type: api.Send, Data: payload}); err != nil {
		t.Fatal("WriteRequest: ", err)
	}
	if _, err := send1.Write(reqData); err != nil {
		t.Fatal("Write(reqData): ", err)
	}
	if err = send1.Close(); err != nil {
		t.Fatal("send1.Close(): ", err)
	}

	// Read response to the listener
	resp, err := api.ReadResponse(lis1)
	if err != nil {
		t.Fatal("ReadResponse: ", err)
	}
	if err = lis1.Close(); err != nil {
		t.Fatal("lis1.Close()")
	}

	// Check that the response matches
	if resp.Channel != ch {
		t.Fatalf("Unexpected channel: %d, want: %d", resp.Channel, ch)
	}
	if !bytes.Equal(resp.Data, payload) {
		t.Fatalf("Unexpected payload: %v, want: %v", resp.Data, payload)
	}

	// Make sure, there was no errors
	select {
	case err := <-errChan:
		t.Fatal("Error reported via errChan:", err)
	default:
	}
}
开发者ID:krasin,项目名称:butovo,代码行数:55,代码来源:sim_test.go

示例5: fightN

func fightN(f1, f2 Factory, n int) []MatchResult {
	aiA := &aiAdapter{factory: f1, games: make(map[string]gameState)}
	aiB := &aiAdapter{factory: f2, games: make(map[string]gameState)}

	a1, a2 := net.Pipe()
	b1, b2 := net.Pipe()

	ca1, ca2 := rpc.StreamTransport(a1), rpc.StreamTransport(a2)
	cb1, cb2 := rpc.StreamTransport(b1), rpc.StreamTransport(b2)

	// Server-side
	srvA := botapi.Ai_ServerToClient(aiA)
	srvB := botapi.Ai_ServerToClient(aiB)
	serverConnA := rpc.NewConn(ca1, rpc.MainInterface(srvA.Client))
	serverConnB := rpc.NewConn(cb1, rpc.MainInterface(srvB.Client))
	defer serverConnA.Wait()
	defer serverConnB.Wait()

	// Client-side
	ctx := context.Background()

	clientConnA := rpc.NewConn(ca2)
	clientConnB := rpc.NewConn(cb2)
	defer clientConnA.Close()
	defer clientConnB.Close()

	clientA := localAI{botapi.Ai{Client: clientConnA.Bootstrap(ctx)}}
	clientB := localAI{botapi.Ai{Client: clientConnB.Bootstrap(ctx)}}

	matchRes := make([]MatchResult, n)
	// Run the game
	for i := 0; i < n; i++ {
		b := engine.EmptyBoard(engine.DefaultConfig)
		b.InitBoard(engine.DefaultConfig)

		for !b.IsFinished() {
			turnCtx, _ := context.WithTimeout(ctx, 30*time.Second)
			resA, _ := clientA.takeTurn(turnCtx, strconv.Itoa(i), b, engine.P1Faction)
			resB, _ := clientB.takeTurn(turnCtx, strconv.Itoa(i), b, engine.P2Faction)
			b.Update(resA, resB)
		}
		matchRes[i] = MatchResult{
			P1Score: b.BotCount(1),
			P2Score: b.BotCount(2),
		}
	}
	return matchRes
}
开发者ID:bcspragu,项目名称:Gobots,代码行数:48,代码来源:local.go

示例6: TestNegotiateRevisionStopResponse

// TestNegotiateRevisionStopResponse tests that when the host sends
// StopResponse, the renter continues processing the revision instead of
// immediately terminating.
func TestNegotiateRevisionStopResponse(t *testing.T) {
	// simulate a renter-host connection
	rConn, hConn := net.Pipe()

	// handle the host's half of the pipe
	go func() {
		defer hConn.Close()
		// read revision
		encoding.ReadObject(hConn, new(types.FileContractRevision), 1<<22)
		// write acceptance
		modules.WriteNegotiationAcceptance(hConn)
		// read txn signature
		encoding.ReadObject(hConn, new(types.TransactionSignature), 1<<22)
		// write StopResponse
		modules.WriteNegotiationStop(hConn)
		// write txn signature
		encoding.WriteObject(hConn, types.TransactionSignature{})
	}()

	// since the host wrote StopResponse, we should proceed to validating the
	// transaction. This will return a known error because we are supplying an
	// empty revision.
	_, err := negotiateRevision(rConn, types.FileContractRevision{}, crypto.SecretKey{})
	if err != types.ErrFileContractWindowStartViolation {
		t.Fatalf("expected %q, got \"%v\"", types.ErrFileContractWindowStartViolation, err)
	}
	rConn.Close()

	// same as above, but send an error instead of StopResponse. The error
	// should be returned by negotiateRevision immediately (if it is not, we
	// should expect to see a transaction validation error instead).
	rConn, hConn = net.Pipe()
	go func() {
		defer hConn.Close()
		encoding.ReadObject(hConn, new(types.FileContractRevision), 1<<22)
		modules.WriteNegotiationAcceptance(hConn)
		encoding.ReadObject(hConn, new(types.TransactionSignature), 1<<22)
		// write a sentinel error
		modules.WriteNegotiationRejection(hConn, errors.New("sentinel"))
		encoding.WriteObject(hConn, types.TransactionSignature{})
	}()
	expectedErr := "host did not accept transaction signature: sentinel"
	_, err = negotiateRevision(rConn, types.FileContractRevision{}, crypto.SecretKey{})
	if err == nil || err.Error() != expectedErr {
		t.Fatalf("expected %q, got \"%v\"", expectedErr, err)
	}
	rConn.Close()
}
开发者ID:robvanmieghem,项目名称:Sia,代码行数:51,代码来源:negotiate_test.go

示例7: BenchmarkWithHack

func BenchmarkWithHack(b *testing.B) {
	client, srv := net.Pipe()
	done := make(chan struct{})
	req := []byte("GET /foo\nHost: /var/run/docker.sock\nUser-Agent: Docker\n")
	read := make([]byte, 4096)
	b.SetBytes(int64(len(req) * 30))

	l := MalformedHostHeaderOverrideConn{client, true}
	go func() {
		for {
			if _, err := srv.Write(req); err != nil {
				srv.Close()
				break
			}
			l.first = true // make sure each subsequent run uses the hack parsing
		}
		close(done)
	}()

	for i := 0; i < b.N; i++ {
		for i := 0; i < 30; i++ {
			if n, err := l.Read(read); err != nil && err != io.EOF {
				b.Fatalf("read: %d - %d, err: %v\n%s", n, len(req), err, string(read[:n]))
			}
		}
	}
	l.Close()
	<-done
}
开发者ID:Tenk42,项目名称:docker,代码行数:29,代码来源:malformed_host_override_test.go

示例8: testMaliciousInput

func testMaliciousInput(t *testing.T, data []byte) {
	w, r := net.Pipe()
	defer w.Close()
	defer r.Close()

	go func() {
		// This io.Copy will discard all bytes from w until w is closed.
		// This is needed because sends on the net.Pipe are synchronous, so
		// the v3Conn will block if we don't read whatever it tries to send.
		// The reason this works is that ioutil.devNull implements ReadFrom
		// as an infinite loop, so it will Read continuously until it hits an
		// error (on w.Close()).
		_, _ = io.Copy(ioutil.Discard, w)
	}()

	go func() {
		// Write the malicious data.
		if _, err := w.Write(data); err != nil {
			panic(err)
		}

		// Sync and terminate if a panic did not occur to stop the server.
		// We append a 4-byte trailer to each to signify a zero length message. See
		// lib/pq.conn.sendSimpleMessage for a similar approach to simple messages.
		_, _ = w.Write([]byte{byte(clientMsgSync), 0x00, 0x00, 0x00, 0x04})
		_, _ = w.Write([]byte{byte(clientMsgTerminate), 0x00, 0x00, 0x00, 0x04})
	}()

	v3Conn := makeTestV3Conn(r)
	_ = v3Conn.serve(nil)
}
开发者ID:yaojingguo,项目名称:cockroach,代码行数:31,代码来源:v3_test.go

示例9: testClientHelloFailure

func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
	// Create in-memory network connection,
	// send message to server. Should return
	// expected error.
	c, s := net.Pipe()
	go func() {
		cli := Client(c, testConfig)
		if ch, ok := m.(*clientHelloMsg); ok {
			cli.vers = ch.vers
		}
		cli.writeRecord(recordTypeHandshake, m.marshal())
		c.Close()
	}()
	hs := serverHandshakeState{
		c: Server(s, serverConfig),
	}
	_, err := hs.readClientHello()
	s.Close()
	if len(expectedSubStr) == 0 {
		if err != nil && err != io.EOF {
			t.Errorf("Got error: %s; expected to succeed", err)
		}
	} else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
		t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr)
	}
}
开发者ID:hurkgu,项目名称:go,代码行数:26,代码来源:handshake_server_test.go

示例10: TestServerDisconnect

func TestServerDisconnect(t *testing.T) {
	spipe, cpipe := net.Pipe()
	cxport := New(cpipe, nil)
	sxport := New(spipe, nil)
	defer sxport.Close()

	// Client side
	client := make(chan string)
	cxport.ToChan(client)
	defer cxport.Close()

	// Disconnect the server
	spipe.Close()

	// Did the client channel get closed?
	select {
	case _, ok := <-client:
		if ok {
			t.Errorf("Real value received?!")
			return
		}
	case <-time.After(100 * time.Millisecond):
		t.Errorf("timeout waiting for client channel close")
		panic("for stack trace")
	}
}
开发者ID:hotei,项目名称:fatchan,代码行数:26,代码来源:fatchan_test.go

示例11: TestConnPubKeyFilter

func TestConnPubKeyFilter(t *testing.T) {
	s1 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc)
	s2 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc)

	c1, c2 := net.Pipe()

	// set pubkey filter
	s1.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error {
		if bytes.Equal(pubkey.Bytes(), s2.nodeInfo.PubKey.Bytes()) {
			return fmt.Errorf("Error: pipe is blacklisted")
		}
		return nil
	})

	// connect to good peer
	go s1.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake.
	go s2.AddPeerWithConnection(c2, true)

	// Wait for things to happen, peers to get added...
	time.Sleep(100 * time.Millisecond * time.Duration(4))

	defer s1.Stop()
	defer s2.Stop()
	if s1.Peers().Size() != 0 {
		t.Errorf("Expected s1 not to connect to peers, got %d", s1.Peers().Size())
	}
	if s2.Peers().Size() != 0 {
		t.Errorf("Expected s2 not to connect to peers, got %d", s2.Peers().Size())
	}
}
开发者ID:tendermint,项目名称:go-p2p,代码行数:30,代码来源:switch_test.go

示例12: TestBuffering

func TestBuffering(t *testing.T) {
	c, s := net.Pipe()
	done := make(chan bool)

	clientWCC := &writeCountingConn{Conn: c}
	serverWCC := &writeCountingConn{Conn: s}

	go func() {
		Server(serverWCC, testConfig).Handshake()
		serverWCC.Close()
		done <- true
	}()

	err := Client(clientWCC, testConfig).Handshake()
	if err != nil {
		t.Fatal(err)
	}
	clientWCC.Close()
	<-done

	if n := clientWCC.numWrites; n != 2 {
		t.Errorf("expected client handshake to complete with only two writes, but saw %d", n)
	}

	if n := serverWCC.numWrites; n != 2 {
		t.Errorf("expected server handshake to complete with only two writes, but saw %d", n)
	}
}
开发者ID:kuangchanglang,项目名称:go,代码行数:28,代码来源:handshake_client_test.go

示例13: TestHandshakeServer

func TestHandshakeServer(t *testing.T) {
	c, s := net.Pipe()
	srv := Server(s, testConfig)
	go func() {
		srv.Write([]byte("hello, world\n"))
		srv.Close()
	}()

	defer c.Close()
	for i, b := range serverScript {
		if i%2 == 0 {
			c.Write(b)
			continue
		}
		bb := make([]byte, len(b))
		_, err := io.ReadFull(c, bb)
		if err != nil {
			t.Fatalf("#%d: %s", i, err)
		}
	}

	if !srv.haveVers || srv.vers != 0x0302 {
		t.Errorf("server version incorrect: %v %v", srv.haveVers, srv.vers)
	}

	// TODO: check protocol
}
开发者ID:GNA-SERVICES-INC,项目名称:MoNGate,代码行数:27,代码来源:handshake_server_test.go

示例14: BenchmarkPipeReadWriter

func BenchmarkPipeReadWriter(b *testing.B) {
	s, c := net.Pipe()

	ch_c_w := make(chanPayload, 1024)
	ch_s_w := make(chanPayload, 1024)
	ch_d := make(chanPayload, 1024)

	hf := NewMsgHeaderFactory(pbt.NewMsgProtobufFactory())

	ep_c := NewEndPoint("c", c, ch_c_w, ch_d, hf, nil, nil)
	ep_s := NewEndPoint("s", s, ch_s_w, ch_s_w, hf, nil, nil)

	ep_c.Run()
	ep_s.Run()

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		req := pbt.NewResourceReq()
		req.Id = proto.Uint64(1)
		for pb.Next() {
			ch_c_w <- req
			<-ch_d
		}
	})

}
开发者ID:arthurkiller,项目名称:rpc,代码行数:26,代码来源:router_test.go

示例15: BenchmarkPipeShareRouter

func BenchmarkPipeShareRouter(b *testing.B) {
	r, err := NewRouter(nil, ServiceProcessPayload)
	if err != nil {
		b.FailNow()
	}

	hf := NewMsgHeaderFactory(pbt.NewMsgProtobufFactory())

	r.Run()
	<-time.Tick(1 * time.Millisecond)

	name := "scheduler"
	n := ConcurrentNum
	m := GoRoutineRequests
	for i := 0; i < n; i++ {
		c, s := net.Pipe()
		ep_c := r.newRouterEndPoint(name+string(i), c, hf)
		ep_s := r.newRouterEndPoint("client"+string(n), s, hf)
		r.AddEndPoint(ep_c)
		r.AddEndPoint(ep_s)
	}

	<-time.Tick(1 * time.Millisecond)
	testShareRouter(b, r, n, m)
}
开发者ID:arthurkiller,项目名称:rpc,代码行数:25,代码来源:router_test.go


注:本文中的net.Pipe函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。