我有一个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个字节。
1条答案
按热度按时间bvjveswy1#
在这个答案中,我应用了问题评论中的好建议。设置描述更改的注解。
Run the code on the playground。