Original Post
I''ve been messing around with asynchronous sockets in C# and I''ve been getting some very screwed up exceptions when I try to Shutdown() or Close() a socket.
The socket is a static member of a class (and so are the functions that make it listen, close, and it''s Accept callback)
//Listener socket
private static Socket listener;
Here is the function that starts it listening:
//Initialize server and begin listening
public static bool Init(int listenPort)
{
//Create a socket object
listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
//Start listening on given port
listener.Bind (new IPEndPoint(IPAddress.Any, listenPort));
listener.Listen(MAX_PENDING_CONNECTIONS);
//Setup a callback for notification of connections
listener.BeginAccept (new AsyncCallback(OnConnectRequest), listener);
//Set server started flag
m_serverStarted = true;
//Success
return true;
}
Here is the accept callback
//Connection request
private static void OnConnectRequest(IAsyncResult result)
{
try
{
User newUser = new User();
//Accept connection and spawn new socket
newUser.userSocket = listener.EndAccept(result);
AddNewUser(newUser);
}
catch (ObjectDisposedException)
{
//Socket has been closed
frmMain.instance.Print ("Error", "Connection request on closed socket", Color.Red);
Close();
}
catch (SocketException se)
{
//Socket exception
frmMain.instance.Print ("Socket Error " + se.ErrorCode.ToString(),
se.Message, Color.Red);
}
}
And here is the function that consistently screws up. The one to close the socket:
//Close server
public static bool Close()
{
//Clear server started flag
m_serverStarted = false;
//Release socket
listener.Shutdown(SocketShutdown.Both);
listener.Close();
//Log status
frmMain.instance.Print ("Server", "Listening ended", Color.Blue);
//Success
return true;
}
When it hits the Shutdown() function, I get the following error message:
An unhandled exception of type ''System.Net.Sockets.SocketException'' occurred in system.dll Additional information: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was suppliedThat kind of puzzled me as I''m clearly not using datagram sockets. So, since the Shutdown() function is not strictly necessary, I commented it and tried again. I got a new type of exception
An unhandled exception of type ''System.InvalidOperationException'' occurred in system.dll Additional information: AcceptCallbackThere was no source code to show where the debugger broke (so not in my code). When I take out the call to BeginAccept() the socket closes down properly (unless I uncomment the call to Shutdown()). I updated the .NET Framework to the latest version but the problems persist. Anyone know what the hell is going on? Is it because the callback is in a static function or what?