本文整理汇总了Golang中net.TCPConn.RemoteAddr方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPConn.RemoteAddr方法的具体用法?Golang TCPConn.RemoteAddr怎么用?Golang TCPConn.RemoteAddr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.TCPConn
的用法示例。
在下文中一共展示了TCPConn.RemoteAddr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handler
// handler handles a single TCP Connection
func (t *TcpListener) handler(conn *net.TCPConn, id string) {
// connection cleanup function
defer func() {
t.wg.Done()
conn.Close()
log.Printf("Closed TCP Connection from %s", conn.RemoteAddr())
// Add one connection potential back to channel when this one closes
t.accept <- true
t.forget(id)
}()
scanner := bufio.NewScanner(conn)
for {
select {
case <-t.done:
return
default:
if !scanner.Scan() {
return
}
buf := scanner.Bytes()
select {
case t.in <- buf:
default:
log.Printf(dropwarn, string(buf))
}
}
}
}
示例2: startLink
func (h *Hub) startLink(l *link, conn *net.TCPConn) {
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(time.Second * 60)
l.setConn(conn)
Info("link(%d) start: %v", l.id, conn.RemoteAddr())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
data, err := l.read()
if err != nil {
if err != errPeerClosed {
h.SendCmd(l.id, LINK_CLOSE_SEND)
}
break
}
h.Send(l.id, data)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
err := l._write()
if err != errPeerClosed {
h.SendCmd(l.id, LINK_CLOSE_RECV)
}
}()
wg.Wait()
Info("link(%d) close", l.id)
}
示例3: InitClient
func InitClient(conn *net.TCPConn, devid string) *Client {
client := &Client{
devId: devid,
ctrl: make(chan bool),
MsgOut: make(chan *Pack, 100),
WaitingChannels: make(map[uint32]chan *Message),
NextSeqId: 1,
LastAlive: time.Now(),
}
DevMap.Set(devid, client)
go func() {
log.Tracef("start send routine for %s", conn.RemoteAddr().String())
for {
select {
case pack := <-client.MsgOut:
seqid := pack.client.NextSeqId
pack.msg.Header.Seq = seqid
b, _ := pack.msg.Header.Serialize()
conn.Write(b)
conn.Write(pack.msg.Data)
log.Infof("send msg ok, (%s)", string(pack.msg.Data))
pack.client.NextSeqId += 1
// add reply channel
if pack.reply != nil {
pack.client.WaitingChannels[seqid] = pack.reply
}
case <-client.ctrl:
log.Tracef("leave send routine for %s", conn.RemoteAddr().String())
return
}
}
}()
return client
}
示例4: handleConnection
func handleConnection(clientConn *net.TCPConn) {
if clientConn == nil {
log.Debugf("handleConnection(): oops, clientConn is nil")
return
}
// test if the underlying fd is nil
remoteAddr := clientConn.RemoteAddr()
if remoteAddr == nil {
log.Debugf("handleConnection(): oops, clientConn.fd is nil!")
return
}
ipv4, port, clientConn, err := getOriginalDst(clientConn)
if err != nil {
log.Infof("handleConnection(): can not handle this connection, error occurred in getting original destination ip address/port: %+v\n", err)
return
}
// If no upstream proxies were provided on the command line, assume all traffic should be sent directly
if gProxyServerSpec == "" {
handleDirectConnection(clientConn, ipv4, port)
return
}
// Evaluate for direct connection
ip := net.ParseIP(ipv4)
if ok, _ := director(&ip); ok {
handleDirectConnection(clientConn, ipv4, port)
return
}
handleProxyConnection(clientConn, ipv4, port)
}
示例5: acceptTCP
func (router *Router) acceptTCP(tcpConn *net.TCPConn) {
// someone else is dialing us, so our udp sender is the conn
// on Port and we wait for them to send us something on UDP to
// start.
connRemote := NewRemoteConnection(router.Ourself, nil, tcpConn.RemoteAddr().String())
NewLocalConnection(connRemote, UnknownPeerName, tcpConn, nil, router)
}
示例6: handlerConnection
//处理连接请求
func (this *server) handlerConnection(conn *net.TCPConn) {
defer logger.CatchException()
logger.Infof("New connection coming ... IP=%s ", conn.RemoteAddr())
conn.SetNoDelay(true) //无延迟
conn.SetKeepAlive(true) //保持激活
conn.SetReadBuffer(64 * 1024) //设置读缓冲区大小
conn.SetWriteBuffer(64 * 1024) //设置写缓冲区大小
conn.SetReadDeadline(time.Now().Add(30000000 * time.Second)) //设置读超时
session := network.NewSession(conn)
defer session.Close()
for {
msg, err := session.RecvMSG()
if err != nil {
logger.Infof("RecvMsgs IP=%s err=%v", conn.RemoteAddr(), err.Error())
return
}
ret := this.ProcessMessage(session, msg)
if ret == false {
return
}
}
}
示例7: serve
// serve serves a single accepted connection
func (p *proxy) serve(client *net.TCPConn) {
connected := connectedClients.With(p.labels)
connected.Inc()
defer func() {
connected.Dec()
_ = client.Close()
}()
p.mutex.Lock()
upstreams := make([]Upstream, len(p.upstreams))
copy(upstreams, p.upstreams)
p.mutex.Unlock()
// TODO: proper iterator accounting weights and current # of connections
for i := range upstreams {
j := rand.Intn(i + 1)
upstreams[i], upstreams[j] = upstreams[j], upstreams[i]
}
for _, upstream := range upstreams {
p.log(fmt.Sprintf("connecting from %s to %s", client.RemoteAddr(), upstream))
backend, err := net.Dial("tcp", upstream.Addr())
if err != nil {
p.log(fmt.Sprintf("error connecting from %s to %s: %s", client.RemoteAddr(), upstream.Addr(), err))
connectionErrors.With(prometheus.Labels{"app": p.app, "upstream": upstream.Addr()}).Inc()
continue
}
p.proxyLoop(client, backend.(*net.TCPConn))
break
}
}
示例8: newConn
// NewConn creates a new connection for the sio. It generates the session id and
// prepares the internal structure for usage.
func newConn(serv *Server, fd uint32, nc *net.TCPConn) (c *Conn, err error) {
host, _, err := net.SplitHostPort(nc.RemoteAddr().String())
if err != nil {
serv.Log("mudoo/newConn: GetRemoteAddr:", err)
return
}
c = &Conn{
serv: serv,
fd: fd,
nc: nc,
raddr: host,
online: true,
lastConnected: time.Now().UnixNano(),
wakeupFlusher: make(chan byte),
wakeupReader: make(chan byte),
numConns: 0,
numHeartbeats: 0,
decBuf: new(Buffer),
}
nc.SetReadBuffer(serv.config.ReadBufferSize)
nc.SetWriteBuffer(serv.config.WriteBufferSize)
go c.keepalive()
// go c.flusher()
go c.reader()
return
}
示例9: Init
func (cl *SrvClient) Init(conn *net.TCPConn) {
cl.Conn = conn
cl.Connected = true
WriteToLogFile("Server", fmt.Sprintf("Client:%v connected\n", conn.RemoteAddr()))
cl.Conn.SetReadDeadline(time.Now().Add(time.Duration(envConfig.Configs.Server.Timeout) * time.Second))
cl.Read()
}
示例10: serve
func serve(c *net.TCPConn) {
ret := c.RemoteAddr().(*net.TCPAddr).IP.String()
_, err := c.Write([]byte(ret))
logError(err)
err = c.Close()
logError(err)
}
示例11: handleConn
// handleConn handles a single incoming TCP connection
func (m *Memberlist) handleConn(conn *net.TCPConn) {
m.logger.Printf("[DEBUG] memberlist: Responding to push/pull sync with: %s", conn.RemoteAddr())
defer conn.Close()
metrics.IncrCounter([]string{"memberlist", "tcp", "accept"}, 1)
join, remoteNodes, userState, err := m.readRemoteState(conn)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to receive remote state: %s", err)
return
}
if err := m.sendLocalState(conn, join); err != nil {
m.logger.Printf("[ERR] memberlist: Failed to push local state: %s", err)
}
if err := m.verifyProtocol(remoteNodes); err != nil {
m.logger.Printf("[ERR] memberlist: Push/pull verification failed: %s", err)
return
}
// Merge the membership state
m.mergeState(remoteNodes)
// Invoke the delegate for user state
if m.config.Delegate != nil {
m.config.Delegate.MergeRemoteState(userState, join)
}
}
示例12: NewTcpTask
func (netservice *NetService) NewTcpTask(conn *net.TCPConn) {
fmt.Println(conn.RemoteAddr())
fmt.Println(conn.LocalAddr())
/*
go func (conn *net.TCPConn) {
readdata := make([]byte,1000)
for true {
_,err := conn.Read(readdata)
if err == nil {
fmt.Println("========",readdata)
msg := &MsgDefine.BaseMsg{}
proto.Unmarshal(readdata[4:],msg)
basemsg := msg.String()
fmt.Println("basemsg",basemsg)
fmt.Printf("%s===\n",basemsg)
} else {
fmt.Println("close================ error")
conn.Close()
break
}
}
}(conn)
*/
}
示例13: TCPReceive
func TCPReceive(connection *net.TCPConn, channelRecieve <-chan config.NetworkMessage) {
for {
message, _ := bufio.NewReader(connection).ReadByte(byte('\x00'))
recievedMessage := config.NetworkMessage{recievedAddress: connection.RemoteAddr(), data: message, length: len(message)}
channelRecieve <- receivedMessage
}
}
示例14: handleClient
func handleClient(source *net.TCPConn) {
atomic.AddInt32(&daemon.status.actives, 1)
defer func() {
atomic.AddInt32(&daemon.status.actives, -1)
daemon.wg.Done()
}()
// read req
err, req := ReadReq(source)
if err != nil {
source.Close()
Error("conn:%v, read req failed:%v", source.RemoteAddr(), err)
return
}
source.SetKeepAlive(true)
source.SetKeepAlivePeriod(time.Second * 60)
source.SetLinger(-1)
// judge: new conn or reuse conn
switch req := req.(type) {
case *NewConnReq:
Info("new conn request:%v", req)
onNewConn(source, req)
case *ReuseConnReq:
Info("reuse conn request:%v", req)
onReuseConn(source, req)
default:
Info("unknown request:%v", req)
source.Close()
return
}
}
示例15: onNewConn
func onNewConn(source *net.TCPConn, req *NewConnReq) {
settings := daemon.settings
host := chooseHost(settings.weight, settings.Hosts)
if host == nil {
source.Close()
Error("choose host failed:%v", source.RemoteAddr())
return
}
dest, err := net.DialTCP("tcp", nil, host.addr)
if err != nil {
source.Close()
Error("connect to %s failed: %s", host.addr, err.Error())
return
}
dest.SetKeepAlive(true)
dest.SetKeepAlivePeriod(time.Second * 60)
dest.SetLinger(-1)
id := <-daemon.nextidCh
link := NewStableLink(id, source, dest, req.key)
daemon.eventCh <- link
link.Run()
daemon.eventCh <- link
link.Wait()
}