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这个方法,好戏都在这里。
相关文章推荐
- Go 语言 Channel 实现原理精要
- Go语言将支持Android
- Golang实现的聊天程序服务端和客户端代码分享
- Golang学习笔记(三):控制流
- Golang学习笔记(二):类型、变量、常量
- Golang中的sync.WaitGroup用法实例
- Go语言struct类型介绍
- golang使用正则表达式解析网页
- Golang极简入门教程(三):并发支持
- Golang极简入门教程(四):编写第一个项目
- Golang记录、计算函数执行耗时、运行时间的一个简单方法
- Golang学习笔记(四):array、slice、map
- 理解Golang中的数组(array)、切片(slice)和map
- golang语言中for循环语句用法实例
- Golang学习笔记(一):简介
- golang操作mongodb的方法
- GO语言(golang)基础知识
- ubuntu下搭建Go语言(golang)环境
- Golang 内存模型详解(一)
- 在Golang中使用C语言代码实例