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


Golang net.Conn函数代码示例

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


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

示例1: acceptUDP

func (s *Server) acceptUDP() {
	// Looping for new messages
	for {
		buf := make([]byte, MAX_MSG_SIZE)
		n, adr, err := s.udpsock.ReadFrom(buf)

		if s.comm.running {
			if err != nil {
				log.Error("Error while reading UDP (read %d) from %s: %s\n", n, adr, err)

			} else {
				abcon := net.Conn(s.udpsock)
				connection := NewConnection(s.comm.pool, P_UDP, D_Inbound, abcon)
				read := io.Reader(bytes.NewBuffer(buf))
				msg := s.comm.NewMessage()
				msg.connection = connection
				err := msg.readMessage(read)

				if err != nil {
					log.Error("Couldn't handle message received from UDP because of errors: %s %s\n", msg, err)
				} else {
					go s.comm.handleMessage(msg)
				}
			}
		} else {
			log.Info("Dropping connection because communications have been paused")
		}
	}
}
开发者ID:appaquet,项目名称:gostore,代码行数:29,代码来源:server.go

示例2: NewDirectRPCClient

// NewDirectRPCClient creates a rpc client
func NewDirectRPCClient(c *Client, clientCodecFunc ClientCodecFunc, network, address string, timeout time.Duration) (*rpc.Client, error) {
	//if network == "http" || network == "https" {
	if network == "http" {
		return NewDirectHTTPRPCClient(c, clientCodecFunc, network, address, "", timeout)
	}

	var conn net.Conn
	var tlsConn *tls.Conn
	var err error

	if c != nil && c.TLSConfig != nil {
		dialer := &net.Dialer{
			Timeout: timeout,
		}
		tlsConn, err = tls.DialWithDialer(dialer, network, address, c.TLSConfig)
		//or conn:= tls.Client(netConn, &config)

		conn = net.Conn(tlsConn)
	} else {
		conn, err = net.DialTimeout(network, address, timeout)
	}

	if err != nil {
		return nil, err
	}

	if c == nil || c.PluginContainer == nil {
		return rpc.NewClientWithCodec(clientCodecFunc(conn)), nil
	}
	return rpc.NewClientWithCodec(newClientCodecWrapper(c.PluginContainer, clientCodecFunc(conn))), nil
}
开发者ID:xxxlihui,项目名称:rpcx,代码行数:32,代码来源:client.go

示例3: HandleStartTLS

// HandleStartTLS is the companion to StartTLS, and will do the connection upgrade.  It assumes
// that the TLS command byte has already been read.  Like StartTLS it returns the peer name, or
// an error
func (p *Protocol) HandleStartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) {
	var (
		err     error
		tlsConn *tls.Conn
	)

	// Build the config
	config := new(tls.Config)
	config.ClientAuth = tls.RequireAndVerifyClientCert

	// Setup the tls connection
	if err := p.tlsSetup(config, identity, caCertificate); err != nil {
		return "", err
	}

	// Upgrade the connection to TLS
	// TODO: Add a deadline here?
	tlsConn = tls.Server(p.conn, config)
	if err = tlsConn.Handshake(); err != nil {
		return "", err
	}

	// Capture the connection state
	cs := tlsConn.ConnectionState()

	// And replace the original connection
	p.conn = net.Conn(tlsConn)
	p.setupBuffers()

	// Send an Ack
	p.Ack()

	return cs.PeerCertificates[0].Subject.CommonName, nil
}
开发者ID:borgstrom,项目名称:reeve,代码行数:37,代码来源:protocol.go

示例4: StartTLS

// StartTLS takes an identity and an authority certificate and upgrades the net.Conn on the protocol to TLS
// It returns the CommonName from the peer certitifcate, or an error
func (p *Protocol) StartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) {
	var (
		err     error
		tlsConn *tls.Conn
	)

	if err = p.WriteBytesWithDeadline([]byte{TLS}); err != nil {
		return "", err
	}

	// Build the config
	config := new(tls.Config)
	config.ServerName = p.serverName

	// Setup the tls connection
	if err = p.tlsSetup(config, identity, caCertificate); err != nil {
		return "", err
	}

	// Upgrade the connection to TLS
	// TODO: Add a deadline here?
	tlsConn = tls.Client(p.conn, config)
	if err = tlsConn.Handshake(); err != nil {
		return "", err
	}

	// Capture the connection state
	cs := tlsConn.ConnectionState()

	// And replace the original connection
	p.conn = net.Conn(tlsConn)
	p.setupBuffers()

	return cs.PeerCertificates[0].Subject.CommonName, nil
}
开发者ID:borgstrom,项目名称:reeve,代码行数:37,代码来源:protocol.go

示例5: SNIHost

// SNIHost will try preempt the TLS handshake and try to sniff the
// Server Name Indication.  It returns `Host()` for non CONNECT
// requests, so it is always safe to call.  If it sniffed
// successfully, but didn't find anything, it is possible to return an
// empty string.
func (ctx *ProxyCtx) SNIHost() string {
	if ctx.Method != "CONNECT" {
		return ctx.Host()
	}

	if ctx.sniffedTLS {
		return ctx.sniHost
	}

	ctx.Conn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))

	tlsConn, err := vhost.TLS(ctx.Conn)
	ctx.Conn = net.Conn(tlsConn)
	ctx.sniffedTLS = true
	if err != nil {
		ctx.Logf("Failed to sniff SNI (falling back to request Host): %s", err)
		return ctx.Host()
	}

	// TODO: make sure we put a ":port" on the `host` if there was one previously...
	sniHost := tlsConn.Host()

	if sniHost != "" {
		ctx.SetDestinationHost(inheritPort(sniHost, ctx.Host()))
		ctx.sniHost = ctx.Host()
	}
	return ctx.sniHost
}
开发者ID:stoplightio,项目名称:goproxy,代码行数:33,代码来源:ctx.go

示例6: TestIssue292

func TestIssue292(t *testing.T) {
	// The util/conn.Manager won't attempt to reconnect to the provided endpoint
	// if the endpoint is initially unavailable (e.g. dial tcp :8080:
	// getsockopt: connection refused). If the endpoint is up when
	// conn.NewManager is called and then goes down/up, it reconnects just fine.

	var (
		tickc    = make(chan time.Time)
		after    = func(time.Duration) <-chan time.Time { return tickc }
		dialconn = net.Conn(nil)
		dialerr  = errors.New("fail")
		dialer   = func(string, string) (net.Conn, error) { return dialconn, dialerr }
		mgr      = NewManager(dialer, "netw", "addr", after, log.NewNopLogger())
	)

	if conn := mgr.Take(); conn != nil {
		t.Fatal("first Take should have yielded nil conn, but didn't")
	}

	dialconn, dialerr = &mockConn{}, nil
	select {
	case tickc <- time.Now():
	case <-time.After(time.Second):
		t.Fatal("manager isn't listening for a tick, despite a failed dial")
	}

	if !within(time.Second, func() bool {
		return mgr.Take() != nil
	}) {
		t.Fatal("second Take should have yielded good conn, but didn't")
	}
}
开发者ID:crezam,项目名称:kit,代码行数:32,代码来源:manager_test.go

示例7: startTLS

func (t *TCP) startTLS() (el element.Element, err error) {
	var tlsConn *tls.Conn
	if t.mode == stream.Initiating {
		err = t.WriteElement(element.StartTLS)
		if err != nil {
			return
		}
		el, err = t.Next()
		if err != nil || el.Tag != element.TLSProceed.Tag {
			return
		}
		tlsConn = tls.Client(t.Conn, t.conf)
	} else {
		err = t.WriteElement(element.TLSProceed)
		if err != nil {
			return
		}
		tlsConn = tls.Server(t.Conn, t.conf)
	}

	err = tlsConn.Handshake()
	if err != nil {
		return
	}
	conn := net.Conn(tlsConn)
	t.Conn = conn
	t.Decoder = xml.NewDecoder(conn)
	el = element.Element{}
	err = stream.ErrRequireRestart
	t.secure = true
	log.Println("Done upgrading connection")
	return
}
开发者ID:skriptble,项目名称:nine,代码行数:33,代码来源:tcp.go

示例8: Start

func (server *TcpServer) Start() (err error) {
	for {
		var conn *net.TCPConn
		if conn, err = server.TCPListener.AcceptTCP(); err != nil {
			return err
		}
		if server.keepAlive != nil {
			if err := conn.SetKeepAlive(server.keepAlive.(bool)); err != nil {
				return err
			}
		}
		if server.keepAlivePeriod != nil {
			if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok {
				if err := kap.SetKeepAlivePeriod(server.keepAlivePeriod.(time.Duration)); err != nil {
					return err
				}
			}
		}
		if server.linger != nil {
			if err := conn.SetLinger(server.linger.(int)); err != nil {
				return err
			}
		}
		if server.noDelay != nil {
			if err := conn.SetNoDelay(server.noDelay.(bool)); err != nil {
				return err
			}
		}
		if server.readBuffer != nil {
			if err := conn.SetReadBuffer(server.readBuffer.(int)); err != nil {
				return err
			}
		}
		if server.writerBuffer != nil {
			if err := conn.SetWriteBuffer(server.writerBuffer.(int)); err != nil {
				return err
			}
		}
		if server.deadline != nil {
			if err := conn.SetDeadline(server.deadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.readDeadline != nil {
			if err := conn.SetReadDeadline(server.readDeadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.writerDeadline != nil {
			if err := conn.SetWriteDeadline(server.writerDeadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.config != nil {
			server.ServeTCP(tls.Client(conn, server.config))
		} else {
			server.ServeTCP(conn)
		}
	}
}
开发者ID:jueebushe,项目名称:hprose-go,代码行数:60,代码来源:tcp_service.go

示例9: Accept

func (l *Listener) Accept() (c net.Conn, err error) {
	l.m.Lock()
	defer l.m.Unlock()

	if l.err == nil {
		l.err = errAccepted
		return net.Conn(l.client), nil
	}
	return nil, l.err
}
开发者ID:dullgiulio,项目名称:inetd,代码行数:10,代码来源:client.go

示例10: GetMsgConnection

func (p *Pool) GetMsgConnection(node *cluster.Node) *Connection {
	// TODO: IMPLEMENT THE POOLING

	adr := net.UDPAddr{node.Address, int(node.UdpPort)}
	con, err := net.DialUDP("udp", nil, &adr) // TODO: should use local address instead of nil (implicitly local)
	if err != nil {
		log.Error("NETPOOL: Couldn't create a connection\n", err)
		return nil
	}

	abcon := net.Conn(con)
	connection := NewConnection(p, P_UDP, D_Outbound, abcon)
	return connection
}
开发者ID:appaquet,项目名称:gostore,代码行数:14,代码来源:pool.go

示例11: upgradeToTLS

// Upgrades a client connection to TLS
func (server *server) upgradeToTLS(client *client) bool {
	tlsConn := tls.Server(client.conn, server.tlsConfig)
	err := tlsConn.Handshake()
	if err != nil {
		log.WithError(err).Warn("[%s] Failed TLS handshake", client.RemoteAddress)
		return false
	}
	client.conn = net.Conn(tlsConn)
	client.bufin = newSMTPBufferedReader(client.conn)
	client.bufout = bufio.NewWriter(client.conn)
	client.TLS = true

	return true
}
开发者ID:flashmob,项目名称:go-guerrilla,代码行数:15,代码来源:server.go

示例12: TestRePConn2

func TestRePConn2(t *testing.T) {
	c, err := net.Dial("tcp", "www.baidu.com:80")
	if err != nil {
		t.Errorf("连接错误:%v", err)
	}
	if _, err := c.Write([]byte("GET / HTTP/1.0\r\nHOST:www.baidu.com\r\n\r\n")); err != nil {
		t.Errorf("写错误:", err)
	}
	tConn := TConn{c}

	preconn := NewPreConn(tConn)
	preconn.NewPre()

	// 第一次读取
	b1 := make([]byte, 16384)
	if n, err := preconn.Read(b1); err != nil {
		t.Errorf("读错误:%v", err)
	} else {
		b1 = b1[:n]
	}

	preconn.ResetPreOffset()

	// 预读的实现是只要缓冲区有数据,即使不够也会直接返回而不是阻塞在Read里面
	// 所以这里应该是相同的长度。
	b2 := make([]byte, 16384)
	if n, err := preconn.Read(b2); err != nil {
		t.Errorf("读错误:", err)
	} else {
		b2 = b2[:n]
	}

	if bytes.Equal(b1, b2) != true {
		t.Errorf("预读会退结果不相等")
	}

	preconn.ResetPreOffset()
	conn := net.Conn(preconn)
	b2 = b2[:16384]
	if n, err := conn.Read(b2); err != nil {
		t.Errorf("读错误:%v", err)
	} else {
		b2 = b2[:n]
	}

	if bytes.Equal(b1, b2) != true {
		t.Errorf("预读会退结果不相等")
	}

}
开发者ID:GameXG,项目名称:preRead,代码行数:50,代码来源:preconn_test.go

示例13: notify

func notify(path, msg string) error {
	addr := net.UnixAddr{
		Net:  netType,
		Name: path,
	}
	conn, err := net.DialUnix(netType, nil, &addr)
	if err != nil {
		return err
	}
	defer net.Conn(conn).Close()

	_, err = conn.Write([]byte(msg))
	return err
}
开发者ID:veteranlu,项目名称:cockroach,代码行数:14,代码来源:sdnotify.go

示例14: Reconnect

// Reconnect forces a new connection to the gateway
// If a connection exists it is closed before the creation of a new one
func (c *PersistentClient) Reconnect() error {

	var cert tls.Certificate
	var err error

	if c.isConnected == true {
		c.Close()
	}

	if len(c.client.certificateBase64) == 0 && len(c.client.keyBase64) == 0 {
		// The user did not specify raw block contents, so check the filesystem.
		cert, err = tls.LoadX509KeyPair(c.client.certificateFile, c.client.keyFile)
	} else {
		// The user provided the raw block contents, so use that.
		cert, err = tls.X509KeyPair([]byte(c.client.certificateBase64), []byte(c.client.keyBase64))
	}
	if err != nil {
		return err
	}
	gatewayParts := strings.Split(c.client.gateway, ":")
	conf := &tls.Config{
		Certificates: []tls.Certificate{cert},
		ServerName:   gatewayParts[0],
	}
	if c.ip == "" { // If the ip is not provided pick one
		ip, err := pickGatewayIP(gatewayParts[0])
		if err != nil {
			return err
		}
		c.ip = ip
	}
	conn, err := net.Dial("tcp", c.ip+":"+gatewayParts[1])
	if err != nil {
		return err
	}
	tlsConn := tls.Client(conn, conf)
	err = tlsConn.Handshake()
	if err != nil {
		conn.Close()
		return err
	}
	c.mu.Lock()
	c.conn = net.Conn(tlsConn)
	c.isConnected = true
	c.mu.Unlock()
	log.Printf("Address of %s is %s", c.client.gateway, c.conn.RemoteAddr().String())
	return nil
}
开发者ID:arnaud-lb,项目名称:apns,代码行数:50,代码来源:persistentclient.go

示例15: upgradeSnappy

func (c *Conn) upgradeSnappy() error {
	conn := net.Conn(c.conn)
	if c.tlsConn != nil {
		conn = c.tlsConn
	}
	c.r = snappystream.NewReader(conn, snappystream.SkipVerifyChecksum)
	c.w = snappystream.NewWriter(conn)
	frameType, data, err := ReadUnpackedResponse(c)
	if err != nil {
		return err
	}
	if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) {
		return errors.New("invalid response from Snappy upgrade")
	}
	return nil
}
开发者ID:samuelyao314,项目名称:mygo,代码行数:16,代码来源:conn.go


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