VB.NET本地TCP客户端开发求助:向127.0.0.1:6680收发字符串
问题分析与修正代码
原代码的核心问题
- 未初始化接收缓冲区:
Dim data As Byte()仅声明数组但未分配内存,Stream.Read无法读取任何数据,导致程序卡住或抛出异常 - 缺少发送逻辑:需求要求发送字符串后接收响应,但原代码仅尝试接收,未实现发送步骤
- 类型错误:
Stream.Read返回值为Integer,不应使用Int128类型 - 未实现两次发送-接收流程:原代码只执行了一次接收,不符合需求
修正后的完整代码
Sub Main() ' 目标地址与端口 Dim ip As String = "127.0.0.1" Dim port As Integer = 6680 Dim encoding As System.Text.Encoding = System.Text.Encoding.ASCII ' 第一次发送与接收 Using client As New TcpClient(ip, port) Using stream As NetworkStream = client.GetStream() ' 设置超时,避免无限等待 stream.ReadTimeout = 1000 stream.WriteTimeout = 1000 ' 1. 发送字符串 Dim sendData1 As Byte() = encoding.GetBytes("第一次发送的内容") stream.Write(sendData1, 0, sendData1.Length) ' 2. 接收响应 Dim buffer1 As Byte() = New Byte(1023) {} ' 初始化1KB缓冲区 Dim bytesRead1 As Integer = stream.Read(buffer1, 0, buffer1.Length) Dim response1 As String = encoding.GetString(buffer1, 0, bytesRead1).Replace(vbCrLf, "") MsgBox("第一次响应:" & response1) End Using End Using ' 第二次发送与接收 Using client As New TcpClient(ip, port) Using stream As NetworkStream = client.GetStream() stream.ReadTimeout = 1000 stream.WriteTimeout = 1000 ' 1. 发送字符串 Dim sendData2 As Byte() = encoding.GetBytes("第二次发送的内容") stream.Write(sendData2, 0, sendData2.Length) ' 2. 接收响应 Dim buffer2 As Byte() = New Byte(1023) {} Dim bytesRead2 As Integer = stream.Read(buffer2, 0, buffer2.Length) Dim response2 As String = encoding.GetString(buffer2, 0, bytesRead2).Replace(vbCrLf, "") MsgBox("第二次响应:" & response2) End Using End Using End Sub
关键修正说明
- 使用
Using语句:自动释放TcpClient和NetworkStream资源,无需手动调用Close() - 初始化缓冲区:为接收数据分配足够大小的字节数组(示例中为1KB,可根据实际调整)
- 添加发送逻辑:通过
stream.Write()将字符串转为字节数组后发送 - 修正返回值类型:用
Integer接收Stream.Read的返回值 - 拆分两次发送-接收流程:分别建立连接完成两次操作(若服务端支持长连接,可复用同一个
TcpClient)
额外注意事项
- 若响应数据超过缓冲区大小,需循环读取直到接收完整数据
- 建议添加
Try...Catch异常处理,捕获连接超时、网络中断等异常,避免程序崩溃
内容的提问来源于stack exchange,提问作者Asier Ouekkai Nieto
相关产品推荐
相关产品推荐

