C# TCP 服务器数据发送优化:清除上一次数据避免残留
在 C# TCP 服务器中,使用 socket 对象的 Send 方法发送数据时,该方法会返回发送的字节数。为了清除上一次返回的数据,可以在下一次发送数据前检查上一次发送的字节数是否等于要发送的数据的长度。如果不等于,则需要先清除上一次发送的数据。
以下是一个示例代码:
// 初始化socket对象
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse('127.0.0.1'), 8888);
serverSocket.Bind(endPoint);
// 开始监听
serverSocket.Listen(100);
while (true)
{
// 接收客户端连接
Socket clientSocket = serverSocket.Accept();
// 接收客户端发送的数据
byte[] data = new byte[1024];
int length = clientSocket.Receive(data);
string message = Encoding.UTF8.GetString(data, 0, length);
// 处理客户端发送的数据
string response = 'Hello, ' + message;
// 清除上一次发送的数据
int sent = 0;
while (sent < length)
{
sent += clientSocket.Send(new byte[length - sent]);
}
// 发送处理结果给客户端
clientSocket.Send(Encoding.UTF8.GetBytes(response));
// 关闭客户端连接
clientSocket.Close();
}
在上面的代码中,我们使用了一个循环来清除上一次发送的数据,直到发送的字节数等于要发送的数据的长度为止。然后再发送处理结果给客户端。这样可以确保每次发送的数据都是新的,没有残留的旧数据。
原文地址: https://www.cveoy.top/t/topic/opfY 著作权归作者所有。请勿转载和采集!