.NET套接字TCP侦听器强制退出问题

本文关键字:退出 出问题 侦听器 套接字 TCP NET | 更新日期: 2023-09-27 17:59:56

所以我试图在visualstudio中用.net套接字设置一个TCP服务器/客户端。到目前为止,在客户端关闭应用程序之前,它运行良好。

错误似乎在这里。但我不知道一旦连接被强制关闭,如何停止while循环的运行。

while(true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
}

//服务器代码//

static TcpListener tcpListener = new TcpListener(25000);
    static void Listeners()
    {
        Socket socketForClient = tcpListener.AcceptSocket();
        NetworkStream networkStream;
        System.IO.StreamWriter streamWriter;
        System.IO.StreamReader streamReader;
        if (socketForClient.Connected)
        {
            Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server.");
            networkStream = new NetworkStream(socketForClient);
            streamWriter = new StreamWriter(networkStream);
            streamReader = new StreamReader(networkStream);
            while(true)
            {
                string theString = streamReader.ReadLine();
                Console.WriteLine("Message recieved by client:" + theString);
            }
        }
    }

.NET套接字TCP侦听器强制退出问题

你试过吗?

private bool IsConnected(Socket socketForClient)
{
         get {return !(Socket.Poll(1, SelectMode.SelectRead) 
                                  && socketForClient.Available ==0)}
}

while(IsConnected())
{
    string theString = streamReader.ReadLine();
    Console.WriteLine("Message recieved by client:" + theString);
    // Do Stuff
}