Check if the Socket is connected before sending data.

I am using super simple synchronous C # Sockets for assignment. The purpose is to create a peer-to-peer chat program, so each instance needs to run both a client and a server. My program works fine when I put it in listen mode: (StateBall is an object that passes state variables around)

public void startListening()
{
    lState = new StateBall();
    IPEndPoint peer = new IPEndPoint(StateBall.host, StateBall.port);
    lSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,    
    ProtocolType.Tcp);

    try
    {
        lSocket.Bind(peer);
        lSocket.Listen(10);
        Console.WriteLine("Waiting for a connection...");

        StateBall.updateText("Waiting for a Connection...");

        client = lSocket.Accept();
        StateBall.toSend=StateBall.ourName;

        StateBall.updateText("Connection made! Sending our name...");
...

      

But when I try to start the second instance and connect to the already running instance, it just hangs and won't connect.

From what I've seen on this site and the rest of the internet, I could check for a preexisting connection using something like:

try{
    lsocket.Connect(peer);
}
catch(Exception ex){
    //check for SocketException type and errors
}

      

And then continue with my program, but is there a clean way to integrate this initial check into the existing code? Or is there a better way to check the active host before trying to call Connect on my socket object?

+2


source to share


1 answer


You can and probably should handle multiple simultaneous connections. Just call in a loop and send separate threads to clients. I suppose you are using only one thread, so when the server is busy with one click, it will time out on the client side to try.



+1


source







All Articles