Ok I'm currently experimenting with Sockets and Threads. I have a multithreaded server that opens a listening socket, and spawns a seperate worker thread to handle each connection made to it. To send data back to the Gui it uses a simple void sendmessage(string) delegate which calls the combination EndInvoke(Beginvoke(new sendmessage(thefunction), new object[]{thestring}))
if invokerequired is true.
what happens is, if multiple client connections are accepted and then the client closes out, it deadlocks and doesn't recover.. heres the thread code..
private void LiveThread(Object myso)
{
DateTime lastheard = DateTime.Now;
DateTime nextcheck = lastheard.AddSeconds(10);
Socket ConnSocket = (Socket)myso;
ConnSocket.Blocking=false;
IPEndPoint Rem = (IPEndPoint) ConnSocket.RemoteEndPoint;
SendMessage("Accepted Connection from : " + Rem.Address);
while ((ConnSocket.Connected) && (!stopitall))
{
if (ConnSocket.Available > 0)
{
try
{
byte[] buff = new byte[255];
int NumBytes = ConnSocket.Receive(buff);
lastheard = DateTime.Now;
nextcheck = lastheard.AddSeconds(10);
SendMessage("recvd:" + Encoding.ASCII.GetString(buff, 0, NumBytes));
}
catch (SocketException e)
{
}
}
if (nextcheck.CompareTo(DateTime.Now) <=0 )
{
try
{
ConnSocket.Send(Encoding.ASCII.GetBytes(":PING".To CharArray()));
SendMessage("Sending Ping");
lastheard = DateTime.Now;
nextcheck = lastheard.AddSeconds(10);
}
catch (SocketException)
{
}
}
}
SendMessage("Closing Connection..");
ConnSocket.Shutdown(SocketShutdown.Both);
ConnSocket.Disconnect(false);
ConnSocket.Close();
}
and the delegate and function..
delegate void amsg(string s);
public void SendMessage(string S)
{
if (InvokeRequired)
{
try
{
EndInvoke(BeginInvoke(new amsg(SendMessage), new Object[] { S }));
}
catch (ObjectDisposedException)
{
}
catch (InvalidOperationException)
{
}
}
else
{
textBox3.Text+="\r\n"+S;
textBox3.Select(textBox3.Text.Length, 0);
textBox3.ScrollToCaret();
}
I imagine it has something to do with the invoke.. but I'm not sure... please help.
Xen.