private static void AcceptCallback(IAsyncResult ar) { Socket socket; try { socket = _serverSocket.EndAccept(ar);/* this terminates the accept connection and then opens it up again for another to connect in. This helps facilitate multiple connections*/ } catch (ObjectDisposedException) { Logging.Write("Current Async connection started from BeginAccept has been terminated. This is most likely caused by changing the program into Client mode (ignorable in this case).", 2); return; } catch (ArgumentException) { Logging.Write("Current Async connection started from BeginAccept has been terminated. This is most likely caused by changing the program into Client mode (ignorable in this case).", 2); return; } _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); for (int i = 0; i < Constants.MAX_Clients; i++) { _clients[i] = new ServeClient(); //creating the client IDs if (_clients[i].socket == null) { _clients[i].socket = socket; _clients[i].index = i; _clients[i].IPAddress = socket.RemoteEndPoint.ToString(); _clients[i].startClient(); Logging.Write(String.Format("Connection from '{0}' received", _clients[i].IPAddress), 3); SendConnectionOK(i); return; } } }
public static void SetupServer() // this will set up the actual server { Logging.Write("Setting up the server.", 3); for (int i = 0; i < Constants.MAX_Clients; i++) { _clients[i] = new ServeClient(); } try { if (!Setup) { _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _serverSocket.Bind(new IPEndPoint(IPAddress.Any, Settings.Port)); //binds to a socket and port _serverSocket.Listen(10); //sets the max amount of clients it will listen for - when the server runs in client mode, this should only accept 1. _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); //Begins the accept process followed by a callback } Setup = true; } catch (SocketException e) { Logging.ExceptionWrite(e); Logging.Write("Server setup has failed.", 2); } }