Go 如何编写 Swoole 的 客户端?

junliuxian · · 980 次点击
//处理连接Connection func handleReceive(conn net.Conn) { buf:=new(Buffer) buffer := make([]byte, 2048) tick:=time.Tick(time.Millisecond*200) for { <-tick n, err := conn.Read(buffer) if err != nil { buf.Reset() delete(clients,conn.RemoteAddr().String()); Log(conn.RemoteAddr().String(), "Connection Error:", err) return } buf.Write(buffer[:n]) //解析数据包 //读取定长8个字节i pLength:=8 pBuf:=make([]byte,pLength) for buf.Len()>=pLength{ if _,err:= buf.Read(pBuf,pLength);err==nil{ msg:=string(pBuf) Log(conn.RemoteAddr().String(), "Receive Data:\n",msg ) //conn.Write([]byte("ClientSend:"+msg)) } } } }
#3
更多评论
read可以不指定吧。看返回值,读取多少。
#1
//处理连接Connection func handleReceive(conn net.Conn) { buf:=new(Buffer) buffer := make([]byte, 2048) tick:=time.Tick(time.Millisecond*200) for { <-tick n, err := conn.Read(buffer) if err != nil { buf.Reset() delete(clients,conn.RemoteAddr().String()); Log(conn.RemoteAddr().String(), "Connection Error:", err) return } buf.Write(buffer[:n]) //解析数据包 //读取定长8个字节i pLength:=8 pBuf:=make([]byte,pLength) for buf.Len()>=pLength{ if _,err:= buf.Read(pBuf,pLength);err==nil{ msg:=string(pBuf) Log(conn.RemoteAddr().String(), "Receive Data:\n",msg ) //conn.Write([]byte("ClientSend:"+msg)) } } } }
#2