0

I have the following code:

class MyServer
{

    TcpListener myList;
    Socket socket;

    public MyServer(string ip)
    {
        this.myList = new TcpListener(ip, 12001);
        this.myList.Start();
        Thread t = new Thread(new ThreadStart(GetConnection));
        t.Start();
    }

    public void GetConnection()
    {
        try
        {
            socket = myList.AcceptSocket(); //(1)
        }
        catch
        {
            Console.WriteLine("Error");
        }
    }

    public void StopListening()
    {
        this.myList.Stop();
    }
}

And it works well: I start the server, and if I "regret" I call StopListening() (before connection has been made!) and because I close myList, (1) is failing.

Is there any way to write this code without the try{}catch{} - rewrite GetConnection() as:

public void GetConnection()
{
    while ( myList is open && there is no connection)
    {
         //do nothing
    }
    if (myList is open)
    {
         this.socket = myList.AcceptConnection();
    }
}

or another way? Thanks.

  • 2
    Does this answer your question? [How to check if a socket is connected/disconnected in C#?](https://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c) – Trevor Dec 30 '19 at 13:37
  • No. The link is about checking if a socket is still alive, I ask if there is a socket pending. – user12625244 Dec 31 '19 at 11:05

1 Answers1

0
socket = myList.AcceptSocket()

Is a blocking call, so it will throw an exception if the underlying socket stops Listening so you will need a try/catch anyway for that blocking call.

You could test:

if (myList.Server.IsBound)
{
     this.socket = myList.AcceptConnection();
}

This way you wouldn't block for the next connection unless the socket was actively listening. But like I said if you want the program to be able to stop listening at some point, then this will still throw an exception when you call myList.Stop()

Rowan Smith
  • 1,815
  • 15
  • 29
  • So there is no way to rewrite `GetConnection()` as mentioned? – user12625244 Jan 03 '20 at 09:10
  • There is no way to break out of TcpListener::AcceptConnection() it's a blocking call. As soon as you call that your program will stop execution until either a connection appears on the socket or another thread closes the Listening Socket. If another thread closes the socket, then an exception will be thrown. – Rowan Smith Jan 03 '20 at 11:23