更新时间:2021-11-27 21:59:57
使用 TcpClient 和 TcpListener 类的异步功能.
在您的客户端:
Use the asynchronous capabilities of the TcpClient and TcpListener classes.
In your client:
private TcpClient server = new TcpClient();
async Task Listen()
{
try {
IPAddress IP = IPAddress.Loopback // this is your localhost IP
await server.ConnectAsync(IP,10000); // IP, port number
if(server.Connected) {
NetworkStream stream = server.GetStream();
while (server.Connected) {
byte[ ] buffer = new byte[server.ReceiveBufferSize];
int read = await stream.ReadAsync(buffer, 0, buffer.Length);
if (read > 0 ){
// you have received a message, do something with it
}
}
}
}
catch (Exception ex) {
// display the error message or whatever
server.Close();
}
}