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

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这个方法,好戏都在这里。

转载于:https://my.oschina.net/seago123/blog/498873

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值