正确处理 net.Conn 的读写连接
来源:stackoverflow
时间:2024-03-20 11:18:41 365浏览 收藏
当使用网络连接进行读写时,有时会出现数据丢失或损坏的问题。这可能是由于数据输入服务器的速度过快导致缓冲区溢出或数据处理错误。为了解决此问题,需要正确处理 `net.Conn` 的读写连接,包括使用缓冲读取器和处理读取截止时间。通过这些措施,可以确保从连接中读取的数据不会丢失,并能及时响应客户端的请求。
我正在尝试使用网络连接进行读写。似乎正在发生的情况是,如果数据进入服务器的速度太快,一些数据就会被丢弃或丢失。客户端连接、协商连接,然后我让它快速连续发送 3 个命令来更新状态页面。每个通信都是一个 json 字符串,该字符串被转换为结构并使用存储的密钥进行解码。
如果我多次单击客户端上的请求(每次生成 3 个以 \n 结尾的 json 有效负载),服务器有时会抛出错误:顶级值后的字符 x 无效。我转储了客户端发送的信息,它在客户端看起来像 3 个格式正确的 json 条目;在服务器端,看起来其中一个 json 负载完全丢失,其中一个负载丢失了前 515 个字符。由于缺少前 515 个字符,json 格式错误,因此封送失败。
我的问题是,如何防止从连接读取的数据丢失?我是否遇到了某种竞争条件或错误处理了如何在连接上读取和发送?
下面基本上是我用于客户端连接处理程序的内容。客户端和服务器协商加密连接,因此有多个对模式和 rsa 状态的引用,并且当密钥设置正确时使用模式 4,以便服务器和客户端可以交换命令和结果。在高层,处理程序会派生一个 goroutine,从连接中读取数据并将其发送到通道。该字符串被读取并转换为结构。会话的第一部分专用于“握手”来协商加密密钥并保存会话信息;一旦到达第 4 阶段,该结构就会携带来自客户端的加密命令并将结果发送回,直到连接出错或关闭。
func HandleClientConnection(conClient net.Conn) { defer conClient.Close() chnLogging <- "Connection from " + conClient.RemoteAddr().String() tmTimeout := time.NewTimer(time.Minute * SERVER_INACTIVITY_TIMEOUT_MINUTES) chnCloseConn := make(chan bool) chnDataFromClient := make(chan string, 1000) go func(chnData chan string) { for { netData, err := bufio.NewReader(conClient).ReadString('\n') if err != nil { if !strings.Contains(err.Error(), "EOF") { chnLogging <- "Error from client " + conClient.RemoteAddr().String() + ": " + err.Error() } else { chnLogging <- "Client " + conClient.RemoteAddr().String() + " disconnected" } chnCloseConn <- true return } tmTimeout.Stop() tmTimeout.Reset(time.Minute * SERVER_INACTIVITY_TIMEOUT_MINUTES) chnData <- netData } }(chnDataFromClient) for { select { case <-chnCloseConn: chnLogging <- "Connection listener exiting for " + conClient.RemoteAddr().String() return case <-tmTimeout.C: chnLogging <- "Connection Timeout for " + conClient.RemoteAddr().String() return case strNetData := <-chnDataFromClient: var strctNetEncrypted stctNetEncrypted err := json.Unmarshal([]byte(strNetData), &strctNetEncrypted) CheckErr(err) switch strctNetEncrypted.IntMode { case 1: keyPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048) CheckErr(err) btServerPrivateKey, err := json.Marshal(keyPrivateKey) CheckErr(err) strctClientPubKeys.SetClientPubkey(strctNetEncrypted.BtPubKey, btServerPrivateKey) defer strctClientPubKeys.DelClientPubkey(strctNetEncrypted.BtPubKey) strctConnections.SetConnection(strctNetEncrypted.BtPubKey, conClient) defer strctConnections.DelConnection(strctNetEncrypted.BtPubKey) strctNetResponse := CreateStctNetEncryptedToClient("", strctNetEncrypted.BtPubKey, 2) if strctNetResponse.BtPubKey == nil || strctNetResponse.BtRemotePubKey == nil { chnLogging <- "Error generating stage two response struct" chnCloseConn <- true return } btJSON, err := json.Marshal(strctNetResponse) CheckErr(err) chnLogging <- "Sending stage 2 negotation response" conClient.Write(btJSON) conClient.Write([]byte("\n")) case 2: chnLogging <- "WARNING: Received mode 2 network communication even though I shouldn't have" case 3: chnLogging <- "Received stage 3 negotiation response" strMessage, err := strctNetEncrypted.RSADecrypt() CheckErr(err) if len(strMessage) != 32 { chnLogging <- "Unexpected shared key length; Aborting" chnCloseConn <- true return } strctClientPubKeys.SetClientSharedKey(strMessage, strctNetEncrypted.BtPubKey, conClient.RemoteAddr().String()) case 4: strMessageDecrypted := DecryptPayloadFromClient(strctNetEncrypted) if strMessageDecrypted != "" { if strings.ToLower(strMessageDecrypted) == "close" { chnLogging <- "Client requests disconnection" chnCloseConn <- true return } // Keepalive message; disregard if strMessageDecrypted == "PING" { continue } btResult := InterpretClientCommand(strMessageDecrypted) strctResponse := CreateStctNetEncryptedToClient(string(btResult), strctNetEncrypted.BtPubKey, 4) btJSON, err := json.Marshal(strctResponse) CheckErr(err) conClient.Write(btJSON) conClient.Write([]byte("\n")) } else { chnLogging <- "Invalid command \"" + strMessageDecrypted + "\"" } default: chnLogging <- "ERROR: Message received without mode set" } } } }
正确答案
应用程序将数据吸收到缓冲的读取器中,然后丢弃该读取器以及它可能已缓冲到第一行之后的任何数据。
在连接的生命周期内保留缓冲读取器:
rdr := bufio.newreader(conclient) for { netdata, err := rdr.readstring('\n') ...
您可以通过消除 goroutine 来简化代码(并修复与缓冲区问题无关的其他问题)。使用读取截止时间来处理无响应的服务器。
func HandleClientConnection(conClient net.Conn) { defer conClient.Close() chnLogging <- "Connection from " + conClient.RemoteAddr().String() conClient.SetReadDeadline(time.Minute * SERVER_INACTIVITY_TIMEOUT_MINUTES) scanner := bufio.NewScanner(conClient) for scanner.Scan() { var strctNetEncrypted stctNetEncrypted err := json.Unmarshal(scanner.Bytes(), &strctNetEncrypted) CheckErr(err) switch strctNetEncrypted.IntMode { // Insert contents of switch statement from // question here with references to // chnCloseConn removed. } conClient.SetReadDeadline(time.Minute * SERVER_INACTIVITY_TIMEOUT_MINUTES) } if scanner.Err() != nil { chnLogging <- "Error from client " + conClient.RemoteAddr().String() + ": " + err.Error() } else { chnLogging <- "Client " + conClient.RemoteAddr().String() + " disconnected" } }
理论要掌握,实操不能落!以上关于《正确处理 net.Conn 的读写连接》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习