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


Golang net.Conn类代码示例

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


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

示例1: connectToDest

func (p *multiplexer) connectToDest(frm *frame, key string, tun *Conn) {
	defer func() {
		ex.CatchException(recover())
	}()
	var (
		dstConn net.Conn
		err     error
		target  = string(frm.data)
	)
	dstConn, err = net.DialTimeout("tcp", target, GENERAL_SO_TIMEOUT)
	frm.length = 0
	if err != nil {
		p.router.removePreRegistered(key)
		log.Errorf("Cannot connect to [%s] for %s error: %s\n", target, key, err)
		frm.action = FRAME_ACTION_OPEN_N
		tunWrite2(tun, frm)
	} else {
		if log.V(1) {
			log.Infoln("OPEN", target, "for", key)
		}
		dstConn.SetReadDeadline(ZERO_TIME)
		edge := p.router.register(key, target, tun, dstConn, false) // write edge
		frm.action = FRAME_ACTION_OPEN_Y
		if tunWrite2(tun, frm) == nil {
			p.relay(edge, tun, frm.sid) // read edge
		} else { // send open_y failed
			SafeClose(tun)
		}
	}
}
开发者ID:hangim,项目名称:deblocus,代码行数:30,代码来源:multiplexer.go

示例2: sendSshKeepAlive

// sendSshKeepAlive is a helper which sends a [email protected] request
// on the specified SSH connections and returns true of the request succeeds
// within a specified timeout.
func sendSshKeepAlive(
	sshClient *ssh.Client, conn net.Conn, timeout time.Duration) error {

	errChannel := make(chan error, 2)
	if timeout > 0 {
		time.AfterFunc(timeout, func() {
			errChannel <- TimeoutError{}
		})
	}

	go func() {
		// Random padding to frustrate fingerprinting
		_, _, err := sshClient.SendRequest(
			"[email protected]", true,
			MakeSecureRandomPadding(0, TUNNEL_SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES))
		errChannel <- err
	}()

	err := <-errChannel
	if err != nil {
		sshClient.Close()
		conn.Close()
	}

	return ContextError(err)
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:29,代码来源:tunnel.go

示例3: handleRawConn

// handleRawConn is run in its own goroutine and handles a just-accepted
// connection that has not had any I/O performed on it yet.
func (s *Server) handleRawConn(rawConn net.Conn) {
	conn, authInfo, err := s.useTransportAuthenticator(rawConn)
	if err != nil {
		s.mu.Lock()
		s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
		s.mu.Unlock()
		grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
		rawConn.Close()
		return
	}

	s.mu.Lock()
	if s.conns == nil {
		s.mu.Unlock()
		conn.Close()
		return
	}
	s.mu.Unlock()

	if s.opts.useHandlerImpl {
		s.serveUsingHandler(conn)
	} else {
		s.serveNewHTTP2Transport(conn, authInfo)
	}
}
开发者ID:qband,项目名称:down,代码行数:27,代码来源:server.go

示例4: NewClient

// NewClient returns a new Client instance connected to an IMAP server via conn.
// The function waits for the server to send a greeting message, and then
// requests server capabilities if they weren't included in the greeting. An
// error is returned if either operation fails or does not complete before the
// timeout, which must be positive to have any effect. If an error is returned,
// it is the caller's responsibility to close the connection.
func NewClient(conn net.Conn, host string, timeout time.Duration) (c *Client, err error) {
	log := newDebugLog(DefaultLogger, DefaultLogMask)
	cch := make(chan chan<- *response, 1)

	c = &Client{
		Caps:          make(map[string]bool),
		CommandConfig: defaultCommands(),
		host:          host,
		state:         unknown,
		tag:           *newTagGen(0),
		cmds:          make(map[string]*Command),
		t:             newTransport(conn, log),
		debugLog:      log,
	}
	c.r = newReader(c.t, MemoryReader{}, string(c.tag.id))
	c.Logf(LogConn, "Connected to %v (Tag=%s)", conn.RemoteAddr(), c.tag.id)

	if err = c.greeting(timeout); err != nil {
		c.Logln(LogConn, "Greeting error:", err)
		return nil, err
	}
	c.cch = cch
	go c.receiver(cch)
	runtime.Gosched()
	return
}
开发者ID:sbinet,项目名称:go-imap,代码行数:32,代码来源:client.go

示例5: Accept

func (p *Peer) Accept(conn net.Conn) (_err error) {
	defer conn.Close()

	p.logFields(SERVE, log.Fields{
		"remoteAddr": conn.RemoteAddr(),
	}).Debug("accepted connection")
	defer func() {
		if _err != nil {
			p.logErr(SERVE, _err).Error()
		}
	}()

	var failResp string
	if p.readAcquire() {
		defer p.wg.Done()
	} else {
		failResp = "sync not available, currently mutating"
	}

	remoteConfig, err := p.handleConfig(conn, SERVE, failResp)
	if err != nil {
		return errgo.Mask(err)
	}

	if failResp == "" {
		return p.interactWithClient(conn, remoteConfig, cf.NewBitstring(0))
	}
	return nil
}
开发者ID:cmars,项目名称:conflux,代码行数:29,代码来源:peer.go

示例6: onConn

func (s *Server) onConn(c net.Conn) {
	conn := s.newClientConn(c) //新建一个conn

	defer func() {
		err := recover()
		if err != nil {
			const size = 4096
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)] //获得当前goroutine的stacktrace
			golog.Error("server", "onConn", "error", 0,
				"remoteAddr", c.RemoteAddr().String(),
				"stack", string(buf),
			)
		}

		conn.Close()
	}()

	if allowConnect := conn.IsAllowConnect(); allowConnect == false {
		err := mysql.NewError(mysql.ER_ACCESS_DENIED_ERROR, "ip address access denied by kingshard.")
		conn.writeError(err)
		conn.Close()
		return
	}
	if err := conn.Handshake(); err != nil {
		golog.Error("server", "onConn", err.Error(), 0)
		c.Close()
		return
	}

	conn.Run()
}
开发者ID:jazzsun,项目名称:kingshard,代码行数:32,代码来源:server.go

示例7: handleClient

func handleClient(p1, p2 net.Conn) {
	log.Println("stream opened")
	defer log.Println("stream closed")
	defer p1.Close()
	defer p2.Close()

	// start tunnel
	p1die := make(chan struct{})
	go func() {
		io.Copy(p1, p2)
		close(p1die)
	}()

	p2die := make(chan struct{})
	go func() {
		io.Copy(p2, p1)
		close(p2die)
	}()

	// wait for tunnel termination
	select {
	case <-p1die:
	case <-p2die:
	}
}
开发者ID:caidaoli,项目名称:kcptun,代码行数:25,代码来源:main.go

示例8: handleConnection

/*
 * This function is called by the main to handle the chat functionality of new connection
 * The function reads the user name and saves it, then waits for user messages and broadcast them
 */
func handleConnection(client net.Conn) {
	reader := bufio.NewReader(client)
	//receive the user name
	buff := make([]byte, 512)
	clientNameb, _ := client.Read(buff)
	clientName := string(buff[0:clientNameb])
	newSession.names = append(newSession.names, clientName)
	newSession.connections = append(newSession.connections, client)

	for {
		//receive the user message
		line, err := reader.ReadBytes('\n')
		if err != nil {
			break
		}
		//broadcast client message
		message := clientName + ":" + string(line)
		for _, currentClient := range newSession.connections {
			if currentClient != nil {
				currentClient.Write([]byte(message))
			}
		}

	}
}
开发者ID:Rasha-elhesha,项目名称:ChatRoom,代码行数:29,代码来源:Server.go

示例9: closeConn

/*
	Close a network connection.
*/
func closeConn(t *testing.T, n net.Conn) error {
	err := n.Close()
	if err != nil {
		t.Errorf("Unexpected n.Close() error: %v\n", err)
	}
	return err
}
开发者ID:myaniu,项目名称:stompngo,代码行数:10,代码来源:utils_test.go

示例10: handleClient

func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // 2分钟无接收信息超时
	//func (c *TCPConn) SetReadDeadline(t time.Time) error
	//func (c *TCPConn) SetWriteDeadline(t time.Time) error

	defer conn.Close()

	for {
		request := make([]byte, 128)
		//128 位读取信息
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Println(err)
			break
		}

		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

	}
}
开发者ID:oywc410,项目名称:MYPG,代码行数:29,代码来源:tcpServer2.go

示例11: storageDeleteFile

func (this *StorageClient) storageDeleteFile(tc *TrackerClient, storeServ *StorageServer, remoteFilename string) error {
	var (
		conn   net.Conn
		reqBuf []byte
		err    error
	)

	conn, err = this.pool.Get()
	defer conn.Close()
	if err != nil {
		return err
	}

	th := &trackerHeader{}
	th.cmd = STORAGE_PROTO_CMD_DELETE_FILE
	fileNameLen := len(remoteFilename)
	th.pkgLen = int64(FDFS_GROUP_NAME_MAX_LEN + fileNameLen)
	th.sendHeader(conn)

	req := &deleteFileRequest{}
	req.groupName = storeServ.groupName
	req.remoteFilename = remoteFilename
	reqBuf, err = req.marshal()
	if err != nil {
		return err
	}
	TcpSendData(conn, reqBuf)

	th.recvHeader(conn)
	if th.status != 0 {
		return Errno{int(th.status)}
	}
	return nil
}
开发者ID:zesus19,项目名称:nephele,代码行数:34,代码来源:storage_client.go

示例12: PSyncPipeCopy

func (cmd *cmdSync) PSyncPipeCopy(c net.Conn, br *bufio.Reader, bw *bufio.Writer, offset int64, copyto io.Writer) (int64, error) {
	defer c.Close()
	var nread atomic2.Int64
	go func() {
		defer c.Close()
		for {
			time.Sleep(time.Second * 5)
			if err := sendPSyncAck(bw, offset+nread.Get()); err != nil {
				return
			}
		}
	}()

	var p = make([]byte, 8192)
	for {
		n, err := br.Read(p)
		if err != nil {
			return nread.Get(), nil
		}
		if _, err := copyto.Write(p[:n]); err != nil {
			return nread.Get(), err
		}
		nread.Add(int64(n))
	}
}
开发者ID:morya,项目名称:redis-port,代码行数:25,代码来源:sync.go

示例13: handleConnection

// handleConnection handles an incoming connection
func (p *Provider) handleConnection(conn net.Conn) {
	// Create an RPC server to handle inbound
	pe := &providerEndpoint{p: p}
	rpcServer := rpc.NewServer()
	rpcServer.RegisterName("Client", pe)
	rpcCodec := msgpackrpc.NewCodec(false, false, conn)

	defer func() {
		if !pe.hijacked() {
			conn.Close()
		}
	}()

	for !p.IsShutdown() {
		if err := rpcServer.ServeRequest(rpcCodec); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") {
				p.logger.Printf("[ERR] scada-client: RPC error: %v", err)
			}
			return
		}

		// Handle potential hijack in Client.Connect
		if pe.hijacked() {
			cb := pe.getHijack()
			cb(conn)
			return
		}
	}
}
开发者ID:GauntletWizard,项目名称:vault,代码行数:30,代码来源:provider.go

示例14: handle

func handle(conn net.Conn) {
	defer conn.Close()

	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		ln := scanner.Text()
		fs := strings.Fields(ln)
		// skip blank lines
		if len(fs) < 2 {
			continue
		}

		switch fs[0] {
		case "GET":
			key := fs[1]
			value := data[key]
			fmt.Fprintf(conn, "%s\n", value)
		case "SET":
			if len(fs) != 3 {
				io.WriteString(conn, "EXPECTED VALUE\n")
				continue
			}
			key := fs[1]
			value := fs[2]
			data[key] = value
		case "DEL":
		default:
			io.WriteString(conn, "INVALID COMMAND "+fs[0]+"\n")
		}
	}
}
开发者ID:RaviTezu,项目名称:GolangTraining,代码行数:31,代码来源:main.go

示例15: HandleIncomingSSHConn

func HandleIncomingSSHConn(nConn net.Conn, config *ssh.ServerConfig) {
	DoneCh := make(chan bool)
	go TimeoutConnection(DoneCh, nConn)
	_, chans, reqs, err := ssh.NewServerConn(nConn, config)
	if err == nil {
		DoneCh <- true
	}
	// Right now that we are out of annoying people land.

	defer nConn.Close()
	go HandleSSHrequests(reqs)

	for newChannel := range chans {
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			log.Printf("WARNING - Rejecting %s Because they asked for a chan type %s that I don't have", nConn.RemoteAddr().String(), newChannel.ChannelType())
			continue
		}

		channel, requests, err := newChannel.Accept()
		if err != nil {
			log.Printf("WARNING - Was unable to Accept channel with %s", nConn.RemoteAddr().String())
			return
		}
		go HandleSSHrequests(requests)
		go ServeDOSTerm(channel)
	}

}
开发者ID:countingpine,项目名称:dos_ssh,代码行数:29,代码来源:ssh.go


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