NSQ系列之nsqlookupd代码分析二(初识nsqlookupd tcpServer)
发布时间:2020-12-16 18:39:51 所属栏目:大数据 来源:网络整理
导读:NSQ系列之nsqlookupd代码分析二(初识nsqlookupd tcpServer) 在上一章 nsqlookupd 初探中了解到, nsqlookupd 中开启了一个 tcpServer 和一个 httpServer ,那么今天我们来初步了解下 tcpServer 。 废话不多说,直接上代码吧,简单粗暴点比较好。 type tcpS
NSQ系列之nsqlookupd代码分析二(初识nsqlookupd tcpServer)在上一章 废话不多说,直接上代码吧,简单粗暴点比较好。 type tcpServer struct { ctx *Context //上一章中提到的Contexto } func (p *tcpServer) Handle(clientConn net.Conn) { p.ctx.nsqlookupd.logf("TCP: new client(%s)",clientConn.RemoteAddr()) // The client should initialize itself by sending a 4 byte sequence indicating // the version of the protocol that it intends to communicate,this will allow us // to gracefully upgrade the protocol away from text/line oriented to whatever... //这里有注释了,但是我英文不好,所以还是加上自己的注释吧,如果有错误,欢迎大家指正哦 buf := make([]byte,4) //初始化4个字节的buf,用来获取协议中的版本号 _,err := io.ReadFull(clientConn,buf) if err != nil { p.ctx.nsqlookupd.logf("ERROR: failed to read protocol version - %s",err) return } protocolMagic := string(buf) p.ctx.nsqlookupd.logf("CLIENT(%s): desired protocol magic '%s'",clientConn.RemoteAddr(),protocolMagic) var prot protocol.Protocol switch protocolMagic { case " V1": //如果是 V1,注意4个字节哦,前面有两个空格字符 prot = &LookupProtocolV1{ctx: p.ctx} //初始化一个lookupProtocolV1的指针,将Context 组合进去 具体参考nsq/nsqlookupd/lookup_protocol_v1.go文件里的代码 default: //如果不是 V1 则关闭连接,返回E_BAD_PROTOCOL protocol.SendResponse(clientConn,[]byte("E_BAD_PROTOCOL")) clientConn.Close() p.ctx.nsqlookupd.logf("ERROR: client(%s) bad protocol magic '%s'",protocolMagic) return } //到这里才是整个tcpServer中的重头戏,不过今天就讲到这里了。下一章就重点分析下这个IOLoop err = prot.IOLoop(clientConn) if err != nil { p.ctx.nsqlookupd.logf("ERROR: client(%s) - %s",err) return } } 通过对上面代码的分析,大致了解了 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |