I'm using super-simple synchronous C# Sockets for an assignment. The assignment is too 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?
If this has already been answered somwhere and I missed it please let me know, and thank you in advance for your help.