我具有用于服务器和客户端程序的这些代码。客户程序向服务器发送一个值,服务器读取它。但是在此消息之后,服务器关闭了。 我希望它能够侦听直到整个应用程序关闭。因此,在1个连接关闭之后,它将等待下一个连接,依此类推。
internal static async Task ServerHandler()
{
Console.Writeline("starting server...");
IPAddress b = IPAddress.Any;
TcpListener Server = new TcpListener(b, 5550);
Server.Start();
Console.Writeline("Server Started Sucessfully!");
Console.Writeline("Waiting for Connection...");
TcpClient Client = Server.AcceptTcpClient();
string clientIPAddress = "Connected! => " + IPAddress.Parse(((IPEndPoint)Client.Client.RemoteEndPoint).Address.ToString());
Console.Writeline(clientIPAddress);
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
try
{
Stream MessageStream = Client.GetStream();
bytesRead = MessageStream.Read(message, 0, 4096);
ASCIIEncoding encoder = new ASCIIEncoding();
string recivedMessage = encoder.GetString(message, 0, bytesRead);
Console.Writeline(recivedMessage);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Client.Close();
Server.Stop();
}
}