C#连接TCP服务器成功后关闭连接怎么读取数据
在成功连接到TCP服务器之后,您可以使用Socket.Receive方法来读取数据。以下是一个简单的示例:
using System;
using System.Net.Sockets;
class TcpClientExample {
static void Main() {
// 创建一个TCP客户端
TcpClient client = new TcpClient("localhost", 1234);
// 从网络流中读取数据
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string data = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: {0}", data);
// 关闭连接
client.Close();
}
}
注意,在读取数据之后,必须关闭TCP连接以释放资源
原文地址: http://www.cveoy.top/t/topic/g1h8 著作权归作者所有。请勿转载和采集!