new user to the site here.
I’m working on a simple asynchronous tcp server. My connection listener looks like this.
public static bool Listen(int port)
{
try
{
IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);
listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(ep);
listener.Listen(4);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
return true;
}
catch (Exception e)
{
Console.WriteLine("Unknown exception: {0}", e.ToString());
return false;
}
}
private static void AcceptCallback(IAsyncResult res)
{
try
{
Socket listener = (Socket)res.AsyncState;
Socket inSocket = listener.EndAccept(res);
Console.WriteLine("Accepted handle: {0}", inSocket.Handle);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (SocketException se)
{
Console.WriteLine("SocketException: {0}", se.ErrorCode);
}
catch (Exception e)
{
Console.WriteLine("Unknown exception: {0}", e.ToString());
}
}
Most of the time it works fine, but occasionally listener.EndAccept(res) triggers a socketexception. It has the error code 10054. The error then keeps occurring for every connection attemp until I restart the listener. What could the problem be?
Also an additional question, what should I set my backlog to?
Occasional “connection-resets” are legal. Client may have closed the connection before you start to process. Even when you get that error, you have to continue to accept the other requests.
So,
listener.BeginAcceptshould be infinallyblock