简体   繁体   中英

.NET Socket TCP Listener force quit issue

So i'm trying to setup a TCP server/client in visual studio with .net sockets. And so far it works fine until the client closes the application.

The error appears to be here. But i'm not sure how to stop the while loop from running once the connection has been force closed.

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

//Server Code//

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);
            }
        }
    }

Have you tried ?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM