I'm using multi threaded system.net.socket to listen on a single port. Here is my listening function:
private void StartListening()
{
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Convert.ToInt32(ConfigurationManager.AppSettings["httpPort"].ToString()));
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Blocking = false;
listener.Bind(localEndPoint);
listener.Listen(10);
Globals.InfoLogYaz(_log, Globals.GetCurrentMethod(), "Socket listener is running...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (Exception ex)
{
Globals.ErrorLogYaz(_log, Globals.GetCurrentMethod(), ex.Message, ex.StackTrace);
return;
}
}
Here is my AcceptCallBack:
public static void AcceptCallback(IAsyncResult ar)
{
Socket listener = null;
Socket handler = null;
try
{
_manualResetEvent.Set();
listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (SocketException ex)
{
if (ex.ErrorCode == 10054)
{
// HATA: "An existing connection was forcibly closed by the remote host"
Globals.ErrorLogYaz(_log, Globals.GetCurrentMethod(), "Karşı taraf işlem tamamlanmadan bağlantıyı kapattı!", ex.StackTrace);
}
if (handler != null)
{
handler.Close();
}
if (listener != null)
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
}
catch (Exception ex)
{
Globals.ErrorLogYaz(_log, Globals.GetCurrentMethod(), ex.Message, ex.StackTrace);
if (handler != null)
{
handler.Close();
}
if (listener != null)
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
}
}
The problem is that I keep my Windows application running with a different thread which has a TCP listener. So if that thread gets an exception and stops my application crashes. I tried to use async socket example on this MSDN link. But after first client request my application hangs and cannot accept a new call. Also I don't want to use a while(true) loop because it uses so much CPU.
So how can I keep that application running without while loop?
Thanks