Golang TCP EOF在几乎同时接收消息时

gab6jxml  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(91)

我有一个Golang TCP服务器可以监听一个设备。设备应该发送一个hello消息,然后服务器返回一个hello。之后,设备发送数据。一旦数据被发送,设备发送提交请求以检查是否接收到数据。问题是我没有收到提交请求这几乎就像数据和提交请求是同时发送的,因为记录的时间戳相隔0.1秒。然而,我知道我正在接收一些东西,因为在数据发送后,我在日志中得到了这个:

Device IP: 13.56.127.98:65145, Timestamp: 2023-08-07T21:23:40.893412845Z 
        Error reading header: EOF

下面是服务器代码:

package servers

import (
    "bufio"
    "bytes"
    "encoding/binary"
    "fmt"
    "math/rand"
    "net"
    "time"
)

func Server() {
    PORT := ":8081"
    l, err := net.Listen("tcp", PORT)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer l.Close()
    rand.Seed(time.Now().Unix())

    for {
        c, err := l.Accept()
        if err != nil {
            fmt.Println(err)
            return
        }

        // Set TCP keep-alive settings
        if tcpConn, ok := c.(*net.TCPConn); ok {
            // Enable TCP keep-alive
            tcpConn.SetKeepAlive(true)

            // Set the time period for sending TCP keep-alive probes
            keepAlivePeriod := 60 * time.Hour // Adjust this value as needed
            tcpConn.SetKeepAlivePeriod(keepAlivePeriod)
        }
        go func() {
            defer c.Close()
            handleConnection(c)
        }()
    }
}

func handleConnection(c net.Conn) {
    defer c.Close()

    data := make([]byte, 4096)

    for {
        //log device ip
        fmt.Printf("Device IP: %s, Timestamp: %s \n", c.RemoteAddr().String(), time.Now().Format(time.RFC3339Nano))
        // Read the communication header from the connection
        //_, err := c.Read(data)
        _, err := bufio.NewReader(c).Read(data)
        if err != nil {
            fmt.Println("   Error reading header:", err)
            return
        }

        // Check the sync bytes
        if data[0] != 0x02 || data[1] != 0x55 {
            fmt.Println("   Invalid sync bytes")
            //log actual bytes received
            fmt.Printf("    Received: %02X %02X %02X %02X %02X\n", data[0], data[1], data[2], data[3], data[4])
            return
        }

        // Get the message type from the header
        messageType := data[2]

        // get payload length
        payloadLengthBytes := data[3:5]
        payloadLength := binary.LittleEndian.Uint16(payloadLengthBytes)

        // Handle the different message types
        switch messageType {
        case 0:
            fmt.Println("   Received Hello message:")
            sendHelloResponse(c)
        case 4:
            // Send data records
            fmt.Println("   Received Send data records message:")
        case 5:
            // Commit request
            fmt.Println("   Received Commit request message:")
        // ... more cases follow
        }
    }
}

我假设是for循环和阅读数据的问题。缓冲区的大小也应该足够大,因为每条消息可能总共有500个字节。

bvjveswy

bvjveswy1#

在这个答案中,我应用了问题评论中的好建议。设置描述更改的注解。

func Server() {
    PORT := ":8081"
    l, err := net.Listen("tcp", PORT)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer l.Close()
    // rand.Seed(time.Now().Unix()) NOTE: not needed in GO 1.20 or later.

    for {
        c, err := l.Accept()
        if err != nil {
            fmt.Println(err)
            return
        }

        // Set TCP keep-alive settings
        if tcpConn, ok := c.(*net.TCPConn); ok {
            // Enable TCP keep-alive
            tcpConn.SetKeepAlive(true)

            // Set the time period for sending TCP keep-alive probes
            keepAlivePeriod := 60 * time.Hour // Adjust this value as needed
            tcpConn.SetKeepAlivePeriod(keepAlivePeriod)
        }
        // NOTE: anonymous function eliminated here by
        // eliminating extra call to defer c.Close()
        go handleConnection(c)
    }
}

func handleConnection(c net.Conn) {
    defer c.Close()
    data := make([]byte, 4096)

    // NOTE: create buffer once and reuse.
    br := bufio.NewReader(c)

    for {
        // NOTE: use io.ReadFull to read complete header.
        _, err := io.ReadFull(br, data[:5])
        if err != nil {
            fmt.Println("   Error reading header:", err)
            return
        }

        // Check the sync bytes
        if data[0] != 0x02 || data[1] != 0x55 {
            fmt.Println("   Invalid sync bytes")
            //log actual bytes received
            fmt.Printf("    Received: %02X %02X %02X %02X %02X\n", data[0], data[1], data[2], data[3], data[4])
            return
        }

        // Get the message type from the header
        messageType := data[2]

        // Get payload
        // NOTE: Use io.ReadFUll again.
        payloadLength := binary.LittleEndian.Uint16(data[3:5])
        _, err = io.ReadFull(br, data[:payloadLength])
        if err != nil {
            fmt.Println("   Error reading payload:", err)
            return
        }

        // Handle the different message types
        switch messageType {
        case 0:
            fmt.Println("   Received Hello message:")
            //sendHelloResponse(c)
        case 4:
            // Send data records
            fmt.Println("   Received Send data records message:")
        case 5:
            // Commit request
            fmt.Println("   Received Commit request message:")
            // ... more cases follow
        }
    }
}

Run the code on the playground

相关问题