/// <summary> /// starts listening on the port specified. /// WARNING: Delegates must be thread safe /// </summary> /// <param name="ip">The IP address to listen for. Use "0.0.0.0" or "any" for all IPs</param> /// <param name="port">The port to listen on</param> /// <param name="separator">What signals the end of a message? A good choice is \n</param> /// <param name="clientstatechange">A delegate that is called when a client connects or disconnects</param> /// <param name="clientrequest">A delegate that is called when a client sends a request</param> // TODO: Allow other types of comms, like UDP, IPv6, etc public ServerSocket(string ip, int port, string separator, ClientStateChange clientstatechange, ClientRequest clientrequest) { this.clientchange = clientstatechange; this.clientreq = clientrequest; IPAddress IP; if (ip == "any") IP = IPAddress.Any; else try { byte[] octets = new byte[4]; string[] exploded = ip.Split('.'); for (byte i = 0; i < 4; i++) octets[i] = byte.Parse(exploded[i]); IP = new IPAddress(octets); } catch (Exception) { throw new Exception("IP Address malformed"); } //IP Address should be valid by now, attempt a bind ServerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint remoteEP = new IPEndPoint(IP, port); ServerSock.Bind(remoteEP); this.separator = separator; Listener = new Thread(new ThreadStart(ListenAsync)); Listener.Start(); }
/// <summary> /// starts listening on the port specified. /// WARNING: Delegates must be thread safe /// </summary> /// <param name="ip">The IP address to listen for. Use "0.0.0.0" or "any" for all IPs</param> /// <param name="port">The port to listen on</param> /// <param name="separator">What signals the end of a message? A good choice is \n</param> /// <param name="clientstatechange">A delegate that is called when a client connects or disconnects</param> /// <param name="clientrequest">A delegate that is called when a client sends a request</param> // TODO: Allow other types of comms, like UDP, IPv6, etc public ServerSocket(string ip, int port, string separator, ClientStateChange clientstatechange, ClientRequest clientrequest) { this.clientchange = clientstatechange; this.clientreq = clientrequest; IPAddress IP; if (ip == "any") { IP = IPAddress.Any; } else { try { byte[] octets = new byte[4]; string[] exploded = ip.Split('.'); for (byte i = 0; i < 4; i++) { octets[i] = byte.Parse(exploded[i]); } IP = new IPAddress(octets); } catch (Exception) { throw new Exception("IP Address malformed"); } } //IP Address should be valid by now, attempt a bind ServerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint remoteEP = new IPEndPoint(IP, port); ServerSock.Bind(remoteEP); this.separator = separator; Listener = new Thread(new ThreadStart(ListenAsync)); Listener.Start(); }