using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace MultipleClientAsyncServer
{
class Program
{
private static void Main()
{
// Start the server on port 12345
ListenForClients(12345);
Console.ReadLine();
}
public static async void ListenForClients(int port)
{
using (var listener = new TcpListener(IPAddress.Loopback, port))
{
await listener.StartAsync();
while (true)
{
var client = await listener.AcceptTcpClientAsync();
Console.WriteLine($"New client connected: {client.Client.RemoteEndPoint}");
// Create a new task for processing each client's messages asynchronously
Task.Run(() => ProcessClient(client));
}
}
}
private static async void ProcessClient(TcpClient tcpClient)
{
byte[] buffer = new byte[1024];
NetworkStream stream;
try
{
stream = tcpClient.GetStream();
// Read a message from the client and display it on the server console
while (true)
{
await stream.ReadAsync(buffer, 0, buffer.Length);
string receivedMessage = Encoding.ASCII.GetString(buffer);
Console.WriteLine($"Client: {tcpClient.Client.RemoteEndPoint} - Message: '{receivedMessage}'");
}
}
catch (Exception)
{
// Client disconnected, clean up and close the stream
tcpClient.Close();
return;
}
}
}
}
错误:
错误 CS1061“TcpListener”不包含“StartAsync”的定义,并且找不到接受“TcpListener”类型的第一个参数的可访问扩展方法“StartAsync”(您是否缺少 using 指令或程序集引用?)
MultipleClientAsyncServer C:\User