我尝试用 net.Dial 去编写 TCP 客户端。可是在读取数据的时候我遇到问题了。 read 的时候,需要指定字节长度,能否不指定呢?新手刚接触,还望指点迷津~
感激不尽
更多评论
//处理连接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
//处理连接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