我尝试用 net.Dial 去编写 TCP 客户端。可是在读取数据的时候我遇到问题了。 read 的时候,需要指定字节长度,能否不指定呢?新手刚接触,还望指点迷津~
感激不尽
下面是一段服务端从客户端接收数据包的简化代码:
func (self *ClientConn) recv() {
var err error
defer func() {
if e := recover(); e != nil {
}
self.Close(false)
}()
_buf := make([]byte, 1)
buf := make([]byte, 0)
var bufLen uint32 = 0
var readSize int
var packet *pb.Packet
for {
deadline := time.Now().Add(hb * time.Second)
self.conn.SetReadDeadline(deadline)
readSize, err = self.conn.Read(_buf)
if err != nil {
return
}
if readSize <= 0 {
continue
}
buf = append(buf, _buf[:readSize]...)
bufLen += uint32(readSize)
for {
if bufLen < pb.DATA_LEN_HEAD {
break
}
packLen := (uint32)(pb.BytesToUint16(buf[:pb.DATA_LEN_HEAD]))
if pb.HB_FLAG == packLen {
if err = self.onHeartBeat(); err != nil {
return
}
buf = buf[pb.DATA_LEN_HEAD:]
bufLen -= pb.DATA_LEN_HEAD
continue
}
if packLen > pb.DATA_LEN_LIMIT || packLen < pb.DATA_LEN_HEAD {
err = fmt.Errorf("invalid packet length:%v, buf:%v, conn:%p", packLen, buf, self)
return
}
if bufLen < packLen {
break
}
packetData := buf[:packLen]
packet, err = self.unmarshalPacket(packetData)
if err != nil {
return
}
if err = self.OnRecvPacket(packet); err != nil {
return
}
buf = buf[packLen:]
bufLen -= packLen
continue
}
}
}
#7
更多评论
//处理连接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