我是 TCP 部分的完整初学者,我尝试编写一个主服务器,它应该以小延迟处理超过 500 个客户端。
这是我的第一次尝试,您对如何改进代码有什么建议,还是我的代码完全垃圾!:D
我首先发送一个 Uint16 作为消息大小的指示符
// receive Code!
private byte[] indexBuffer = new byte[sizeof(UInt16)];
private int indexSize = sizeof(UInt16);
public async void receiveData(TcpClient client) {
var result = await Task.Run(() => {
try {
int checkSum = client.Client.Receive(indexBuffer, 0, indexBuffer.Length, SocketFlags.None);
if (checkSum != indexSize) return null;
int packageSize = BitConverter.ToUInt16(indexBuffer, 0);
Console.WriteLine(packageSize);
var recData = new Byte[packageSize];
checkSum = client.Client.Receive(recData, 0, packageSize, SocketFlags.None);
if (checkSum != packageSize) return null;
return Encoding.ASCII.GetString(recData);
} catch(Exception ex) {
Console.WriteLine(ex.Message);
return "-1";
}
});
// blabla do something
Console.WriteLine(result);
//---------------------
if (client.Connected)
receiveData(client);
}