Golang 的 TCP EOF 几乎同时处理接收的消息
来源:stackoverflow
2024-02-08 09:54:24
0浏览
收藏
从现在开始,我们要努力学习啦!今天我给大家带来《Golang 的 TCP EOF 几乎同时处理接收的消息》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!
问题内容
我有一个监听设备的 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 字节。
正确答案
在这个答案中,我应用了问题评论中的好的建议。设置描述更改的注释。
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。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
读取 APIGatewayProxyRequest 的方法:使用 gin.context
- 上一篇
- 读取 APIGatewayProxyRequest 的方法:使用 gin.context
- 下一篇
- 使用容器化技术连接本地 MongoDB 的 Go 应用程序
查看更多
最新文章
-
- Golang · Go问答 | 1天前 |
- Go ColumnTypes 推断动态查询字段的安全用法
- 319浏览 收藏
-
- Golang · Go问答 | 1天前 | Go问答 · Go 错误检查 database/sql Rows.Err
- Go Rows.Err 在迭代结束后的错误检查
- 266浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go sql.Scan NULL 到字符串失败的字段适配
- 388浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go Tx.Stmt 复用预处理语句的生命周期
- 154浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go 事务隔离级别设置未生效的驱动边界
- 165浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go DB PingContext 启动探活的超时配置
- 438浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go database/sql Rows 未关闭造成连接耗尽的诊断
- 354浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go database/sql 连接池 MaxIdleConns 的容量关系
- 478浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go URL 查询值乱码时的编码排查步骤
- 285浏览 收藏
-
- Golang · Go问答 | 1天前 | Go问答 · Go URL路径 url.JoinPath PathEscape 双斜杠
- Go url.JoinPath 处理双斜杠的路径规则
- 446浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 271次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 324次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 314次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 288次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 105次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
