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


Golang Conn.RemoteAddr方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: proxyConnection

// The core of the file: read any input from the connection and outputs it into
// the server connection
func proxyConnection(conn net.Conn, done chan bool) {
	dec := json.NewDecoder(conn)
	nerr := 0
	for {
		m := SingleMeasure{}
		// Receive data
		if err := dec.Decode(&m); err != nil {
			if err == io.EOF {
				break
			}
			log.Lvl1("Error receiving data from", conn.RemoteAddr().String(), ":", err)
			nerr++
			if nerr > 1 {
				log.Lvl1("Too many errors from", conn.RemoteAddr().String(), ": Abort connection")
				break
			}
		}
		log.Lvl3("Proxy received", m)

		// Proxy data back to monitor
		if err := serverEnc.Encode(m); err != nil {
			log.Lvl2("Error proxying data :", err)
			break
		}
		if m.Name == "end" {
			// the end
			log.Lvl2("Proxy detected end of measurement. Closing connection.")
			break
		}
	}
	if err := conn.Close(); err != nil {
		log.Error("Couldn't close connection:", err)
	}
	done <- true
}
开发者ID:nikirill,项目名称:cothority,代码行数:37,代码来源:proxy.go

示例6: handleClient

func handleClient(conn net.Conn) {
	common.Conn2ClientInfo[conn] = &common.ClientInfo{Conn: conn, ClientMap: make(map[net.Conn]*common.Session), Id2Session: make(map[string]*common.Session), IsServer: false, Quit: make(chan bool), ResponseTime: time.Now().Unix()}
	log.Println("client linked success", conn.RemoteAddr().String())
	common.Conn2ClientInfo[conn].Loop()
	common.Read(conn, handleResponse)
	client, bHave := common.Conn2ClientInfo[conn]
	if bHave {
		close(client.Quit)
		if client.IsServer {
			for conn, session := range client.ClientMap {
				conn.Close()
				common.RmId(client.ServerName, session.Id)
			}
			delete(common.ServerName2Conn, client.ServerName)
			log.Println("unregister service Name", client.ServerName)
			if bUseDB {
				user, _ := auth.GetUser(client.UserName)
				if user != nil {
					user.OnLogout()
				}
			}
		} else {
			common.GetServerInfoByConn(conn, func(server *common.ClientInfo) {
				id := server.DelClient(conn)
				log.Println("send quit")
				common.Write(server.Conn, id, "clientquit", "")
			}, func() {})
		}
		delete(common.Conn2ClientInfo, conn)
	}
	conn.Close()
	log.Println("client disconnected", conn.RemoteAddr().String())
}
开发者ID:PengV,项目名称:dog-tunnel,代码行数:33,代码来源:server.go

示例7: handleConn

func handleConn(conn net.Conn) {
	defer conn.Close()
	log.Println("connected from:", conn.RemoteAddr())
	dst, err := dialer.Dial("tcp", *dstAddr)
	if err != nil {
		log.Println(err)
		return
	}
	defer dst.Close()
	wg := &sync.WaitGroup{}
	wg.Add(2)
	go func(wg *sync.WaitGroup) {
		buf := bufferPool.Get()
		_, err = io.CopyBuffer(conn, dst, buf.([]byte))
		if err != nil {
			log.Println(err)
		}
		bufferPool.Put(buf)
		wg.Done()
	}(wg)
	go func(wg *sync.WaitGroup) {
		buf := bufferPool.Get()
		_, err = io.CopyBuffer(dst, conn, buf.([]byte))
		if err != nil {
			log.Println(err)
		}
		bufferPool.Put(buf)
		wg.Done()
	}(wg)
	wg.Wait()
}
开发者ID:ma6174,项目名称:netproxy,代码行数:31,代码来源:proxy.go

示例8: storage_upload_file

func storage_upload_file(header *Header, conn net.Conn) bool {
	buff := make([]byte, header.pkg_len)
	n, err := io.ReadFull(conn, buff)
	if err != nil || n != int(header.pkg_len) {
		return false
	}
	req := &UploadFileRequest{}
	err = req.Unmarshal(buff)
	if err != nil {
		return false
	}

	file_ext := storage_format_ext_name(req.file_ext)
	crc32 := crc32.ChecksumIEEE(req.file_data)
	now := time.Now()
	//	log.Println(req.store_path_index, req.file_length,  len(req.file_data), file_ext, crc32)

	addr, _ := conn.RemoteAddr().(*net.TCPAddr)
	file_name, full_name := storage_get_filename(addr.IP.String(), int(req.store_path_index), int(now.Unix()), req.file_length, int(crc32), file_ext)
	file, err := os.OpenFile(full_name, os.O_WRONLY|os.O_EXCL|os.O_CREATE, 0644)
	if err != nil {
		log.Print(err)
		return send_result(errno(err), conn)
	}
	n, err = file.Write(req.file_data)
	if err != nil || n != len(req.file_data) {
		panic("write")
	}

	file_name = fmt.Sprintf("M00/%s", file_name)
	storage_binlog_write(int(now.Unix()), STORAGE_OP_TYPE_SOURCE_CREATE_FILE, file_name)

	resp := &UploadFileResponse{"group1", file_name}
	return send_response(resp, conn)
}
开发者ID:richmonkey,项目名称:fastdfs-go,代码行数:35,代码来源:storage.go

示例9: handleResponse

func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) {
	defer finish.Unlock()
	defer close(output)
	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
	if err != nil {
		log.Error("VMessOut: Failed to create decrypt reader: %v", err)
		return
	}

	buffer, err := v2net.ReadFrom(decryptResponseReader, nil)
	if err != nil {
		log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", buffer.Len(), err)
		return
	}
	if buffer.Len() < 4 || !bytes.Equal(buffer.Value[:4], request.ResponseHeader[:]) {
		log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
		return
	}
	log.Info("VMessOut received %d bytes from %s", buffer.Len()-4, conn.RemoteAddr().String())

	buffer.SliceFrom(4)
	output <- buffer

	if !isUDP {
		v2net.ReaderToChan(output, decryptResponseReader)
	}

	return
}
开发者ID:xiatiansong,项目名称:v2ray-core,代码行数:32,代码来源:vmessout.go

示例10: handleTCPConn

// hanleTCPConn handle a long live tcp connection.
func handleTCPConn(conn net.Conn, rc chan *bufio.Reader) {
	addr := conn.RemoteAddr().String()
	log.Debug("<%s> handleTcpConn routine start", addr)
	rd := newBufioReader(rc, conn)
	if args, err := parseCmd(rd); err == nil {
		// return buffer bufio.Reader
		putBufioReader(rc, rd)
		switch args[0] {
		case "sub":
			SubscribeTCPHandle(conn, args[1:])
			break
		default:
			conn.Write(ParamReply)
			log.Warn("<%s> unknown cmd \"%s\"", addr, args[0])
			break
		}
	} else {
		// return buffer bufio.Reader
		putBufioReader(rc, rd)
		log.Error("<%s> parseCmd() error(%v)", addr, err)
	}
	// close the connection
	if err := conn.Close(); err != nil {
		log.Error("<%s> conn.Close() error(%v)", addr, err)
	}
	log.Debug("<%s> handleTcpConn routine stop", addr)
	return
}
开发者ID:Terry-Mao,项目名称:gopush-cluster,代码行数:29,代码来源:pubsub_tcp.go

示例11: tunnel

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

	// We start with a JSON header, currenly only has the dest addr.
	hdrdec := json.NewDecoder(conn)
	var hdr header
	err := hdrdec.Decode(&hdr)
	if err != nil {
		log.Printf("Couldn't parse tunnelled connection header: %v", err)
		return
	}

	destc, err := net.Dial("tcp", hdr.Destaddr)
	if err != nil {
		log.Printf("Couldn't dial destination $v: %v", hdr.Destaddr, err)
		return
	}
	defer destc.Close()

	log.Printf("Now tunnelling %v to %v", conn.RemoteAddr(), destc.RemoteAddr())
	done := make(chan struct{})
	go func() {
		io.Copy(destc, io.MultiReader(hdrdec.Buffered(), conn))
		done <- struct{}{}
	}()
	io.Copy(conn, destc)
	<-done
}
开发者ID:saljam,项目名称:dnsproxy,代码行数:28,代码来源:main.go

示例12: handleConn

func handleConn(cid int, usConn net.Conn) {
	defer usConn.Close()

	log.Println(cid, "Handling new connection from", usConn.RemoteAddr())
	log.Println(cid, "Making downstream connection...")
	dsConn, err := makeDownstreamConnection()
	defer dsConn.Close()
	if err != nil {
		log.Println(cid, "Failed upstream", err)
		return
	}

	hp, err := ReadHandshakePacket(usConn)
	if err != nil {
		log.Println(cid, "Failed RHP", err)
		return
	}

	hp2 := MangleHandshakePacket(hp)

	err = WriteHandshakePacket(dsConn, hp2)
	if err != nil {
		log.Println(cid, "Failed WHP", err)
		return
	}

	go io.Copy(usConn, dsConn)
	io.Copy(dsConn, usConn)
}
开发者ID:lukegb,项目名称:notbungee,代码行数:29,代码来源:notbungee.go

示例13: roundtrip

func roundtrip(ctx *ClientContext, conn net.Conn, requestSize, requestBytes []byte) ([]byte, error) {
	deadline, ok := ctx.Deadline()
	if !ok {
		deadline = time.Time{}
	}

	var err error
	if err = conn.SetDeadline(deadline); err != nil {
		return nil, makeClientErr(err.Error())
	}
	if _, err = conn.Write(requestSize); err != nil {
		return nil, makeClientErrf("Failed to write 4 bytes for request size: %s", err)
	}
	if _, err = conn.Write(requestBytes); err != nil {
		return nil, makeClientErrf("Failed to write %d bytes for request: %s", err)
	}
	buf := bytes.NewBuffer(make([]byte, 0, 4))
	if _, err = io.CopyN(buf, conn, 4); err != nil {
		return nil, makeClientErrf(
			"Failed to read 4 bytes for response size from '%s': %s",
			conn.RemoteAddr().String(), err)
	}
	responseSize := binary.BigEndian.Uint32(buf.Bytes())
	if _, err = io.CopyN(buf, conn, int64(responseSize)); err != nil {
		return nil, makeClientErrf(
			"Failed to read %d bytes for response from '%s': %s",
			conn.RemoteAddr().String(), err)
	}
	return buf.Bytes(), nil
}
开发者ID:xinlaini,项目名称:golibs,代码行数:30,代码来源:client.go

示例14: newClientRESP

func newClientRESP(conn net.Conn, app *App) {
	c := new(respClient)

	c.client = newClient(app)
	c.conn = conn

	c.activeQuit = false

	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.SetReadBuffer(app.cfg.ConnReadBufferSize)
		tcpConn.SetWriteBuffer(app.cfg.ConnWriteBufferSize)
	}

	br := bufio.NewReaderSize(conn, app.cfg.ConnReadBufferSize)
	c.respReader = goredis.NewRespReader(br)

	c.resp = newWriterRESP(conn, app.cfg.ConnWriteBufferSize)
	c.remoteAddr = conn.RemoteAddr().String()

	app.connWait.Add(1)

	app.addRespClient(c)

	go c.run()
}
开发者ID:ming-hai,项目名称:ledisdb,代码行数:25,代码来源:client_resp.go

示例15: onConn

func (s *Server) onConn(c net.Conn) {
	conn := s.newClientConn(c)

	defer func() {
		err := recover()
		if err != nil {
			const size = 4096
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)]
			log.Printf("Error server.onConn remoteAddr:%s, stack:%s", c.RemoteAddr().String(), string(buf))
		}

		conn.Close()
	}()

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

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


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