您的位置:首页 > 理论基础 > 计算机网络

NSQ系列之nsqlookupd代码分析二(初识nsqlookupd tcpServer)

2015-08-29 01:13 1041 查看

NSQ系列之nsqlookupd代码分析二(初识nsqlookupd tcpServer)

在上一章
nsqlookupd
初探中了解到,
nsqlookupd
中开启了一个
tcpServer
和一个
httpServer
,那么今天我们来初步了解下
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'",
clientConn.RemoteAddr(), protocolMagic)
return
}
//到这里才是整个tcpServer中的重头戏,不过今天就讲到这里了。下一章就重点分析下这个IOLoop
err = prot.IOLoop(clientConn)
if err != nil {
p.ctx.nsqlookupd.logf("ERROR: client(%s) - %s", clientConn.RemoteAddr(), err)
return
}
}

通过对上面代码的分析,大致了解了
tcpServer
的连接处理过程,下一章就重点介绍
IOLoop
这个方法,好戏都在这里。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nsq nsqd nsqlookupd golang