NateD
NateD

Reputation: 624

Check if a Socket is Connected before sending Data

I'm using super-simple synchronous C# Sockets for an assignment. The assignment is to create a peer-to-peer chat program, so each instance must work as both a client and a server. My program works great when I put it into 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 a second instance and connect to an already running instance it just hangs and doesn't connect.

From what I've seen on this site and the rest of the Web I could check for a pre-existing connection using something like:

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

And then go on with my program, but is there a clean way to integrate that initial check into the already existing code? Or is there a better way to check for an active host before attempting to call Connect on my socket object?

Upvotes: 2

Views: 1271

Answers (1)

jdehaan
jdehaan

Reputation: 19928

You can and probably should handle more than one concurrent connection. Simply call accept in a loop and dispatch the clients on separate threads. I suppose that you only use one thread so when the server is busy with one client connection attempts time out on the client side.

Upvotes: 1

Related Questions