I've run into a bit of a snag while dealing with asynchronous sockets. What I'm trying to do is set a timeout for which the server will listen for a connection from a client, at which point the object maintaining the server side connection will be disposed of through the use of a delegate.
The code is as follows:
Expand|Select|Wrap|Line Numbers
- public Bridge(string[] args, int inPort)
- {
- name = args[0];
- surname = args[1];
- password = args[2];
- // Sort out network related initialization
- port = inPort;
- Logger.Log("Bridge #" + port.ToString() + ": Initializing.", Helpers.LogLevel.Info);
- mainSock = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream,
- ProtocolType.Tcp);
- IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
- mainSock.Bind(ipLocal);
- mainSock.Listen(3);
- // Socket is initialized here
- mainSock.BeginAccept(new AsyncCallback(OnRequest),null);
- timer = new Timer(new TimerCallback(OnTimeout), null, 5000, Timeout.Infinite);
- Logger.Log("Bridge #" + port.ToString() + ": Completed Initialization successfully; waiting for client request.", Helpers.LogLevel.Info);
- }
- private void OnRequest(IAsyncResult result)
- {
- Logger.Log("Bridge #" + port.ToString() + ": Socket request received.", Helpers.LogLevel.Info);
- timer.Dispose();
- // Error gets thrown here after OnTimeout is triggered
- mainSock = mainSock.EndAccept(result);
- inClient = new Client((String[])Tools.ToArray(name, surname, password));
- // bind callback handlers for connections and disconnections of inClient
- inClient.Network.OnLogin += new NetworkManager.LoginCallback(ConnectionHandler);
- inClient.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(DisconnectHandler);
- inClient.Self.OnChat += new AgentManager.ChatCallback(ChatHandler);
- // wait for connection signal
- }
- private void OnTimeout(Object stateInfo)
- {
- Logger.Log("Bridge #" + port.ToString() + ": Connection timed out.", Helpers.LogLevel.Error);
- // Problem lies here
- mainSock.Close();
- timer.Dispose();
- OnBridgeTerm(port - portOffset);
- }
When using Close, I find that no errors are thrown, however, once OnTimeout finishes executing, OnRequest is instantly triggered even though the client clearly has not sent a connection request at all (that code is disabled).
What is the proper way to dispose of this pending socket? Am I even setting up the connection properly to begin with?