2016-03-03 03:47
浏览 43


I am creating a TCP server end in GO, which receives TCP packets and sends responses accordingly. I am able to listen to connections, but when the client-end sends TCP packets to the server, the server only receives them when the connection is reset (TCP RST).

This means that when the client sends a packet, the server waits for the next packet to do something with the first. This is the code affecting this part of the problem:

listener, err := net.Listen("tcp", ":25565")

if err != nil {

for {
  conn, err := listener.Accept()

  if err != nil {

  message, _ := ioutil.ReadAll(conn) // Get the bytes from the TCP packet
  fmt.Println("Received connection " + conn.RemoteAddr().String())
  HandlePacket(conn, message) // Do stuff with the data
  conn.Close() // End the connection

HandlePacket(...) parses the bytes received in the packet. The thing is, it receives nothing when the client sends the first packet, and then prints the first packet's data when the second is sent.

图片转代码服务由CSDN问答提供 功能建议

我正在GO中创建一个TCP服务器端,该端接收TCP数据包并相应地发送响应。 我能够监听连接,但是当客户端将TCP数据包发送到服务器时,服务器仅在重置连接(TCP RST)时才接收它们。

这意味着当客户端发送数据包时,服务器将等待下一个数据包对第一个数据包执行某些操作。 这是影响问题的这一部分的代码:

  listener,错误:= net.Listen(“ tcp”,“:25565”)
if错误!=  nil {
 {{n conn,err:= listener.Accept()
 if err!= nil {
消息,_:= ioutil.ReadAll(conn)//从TCP数据包中获取字节
 fmt.Println(“接收的连接” + conn.RemoteAddr()。String())
 HandlePacket(  conn,message)//处理数据

HandlePacket(.. 。)解析数据包中收到的字节。 事实是,当客户端发送第一个数据包时,它什么也收不到,然后在发送第二个数据包时,打印第一个数据包的数据。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsh84723 2016-03-03 04:10

    The big hint is right there in your call to read from the socket:

    message, _ := ioutil.ReadAll(conn) // Get the bytes from the TCP packet

    ReadAll() won't just return the available data in the socket's buffer. ReadAll() is going to read until there's never going to be any more data to read - until the stream is closed. The stream is closed only when the connection is closed, as you've seen.

    You have to ask the TCP socket to read some finite amount of data. Since TCP does not preserve message boundaries, you have to use your own framing scheme to know how much data to read.

    One such simple scheme is to make it so that your packets are always some fixed size. This might be useful, for instance, if you're sending streaming updates for, say, a game's netcode; just make each packet 256 bytes and stuff in as many position updates as will fit in 256 bytes; if there's more, just send more packets.

    If using a fixed-sized frame doesn't work for you, consider using a packet with a little header. Perhaps the first 4 bytes are an integer telling you how long the message is, followed by the message. Then, every time you want to read a packet, you perform a hard read of 4 bytes to find out the size, and then read that many bytes from the socket.

    解决 无用
    打赏 举报

相关推荐 更多相似问题