public void Stop() { try { if (Running) { bool b = true; if (BeforeStopEvent != null) { b = BeforeStopEvent(); } if (b) { if (UDPListeners != null) { while (UDPListeners.Count > 0) { System.Threading.Thread thread = UDPListeners[0]; if (thread.IsAlive) { thread.Abort(); while (thread.IsAlive) { System.Threading.Thread.Sleep(250); } } UDPListeners.Remove(thread); } } if (TCPListeners != null) { while (TCPListeners.Count > 0) { System.Threading.Thread thread = TCPListeners[0]; if (thread.IsAlive) { thread.Abort(); while (thread.IsAlive) { System.Threading.Thread.Sleep(250); } } TCPListeners.Remove(thread); } } Running = false; if (AfterStopEvent != null) { AfterStopEvent(); } } } } catch (System.Exception ex) { throw ex; } }
private void CreateListeners(System.Net.IPAddress ipaddress) { try { System.Net.Sockets.Socket socket = null; System.Threading.Thread thread = null; try { // Create UDP socket and thread. socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); socket.EnableBroadcast = true; socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, 1); socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.Broadcast, 1); socket.Bind(new System.Net.IPEndPoint(ipaddress, Port)); thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.UDPListenerThread)); thread.Start(socket); UDPListeners.Add(thread); // Create TCP socket and thread. socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); socket.Bind(new System.Net.IPEndPoint(ipaddress, Port)); socket.Listen(MaxConnections); thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.TCPListenerThread)); thread.Start(socket); TCPListeners.Add(thread); } catch (System.Net.Sockets.SocketException ex) { if (thread != null) { if (thread.IsAlive) { thread.Abort(); while (thread.IsAlive) { System.Threading.Thread.Sleep(250); } } } if (socket != null) { if (socket.Connected) { socket.Shutdown(System.Net.Sockets.SocketShutdown.Both); socket.Disconnect(false); } socket.Close(); } throw ex; } catch (System.Exception ex) { if (thread != null) { if (thread.IsAlive) { thread.Abort(); while (thread.IsAlive) { System.Threading.Thread.Sleep(250); } } } if (socket != null) { if (socket.Connected) { socket.Shutdown(System.Net.Sockets.SocketShutdown.Both); socket.Disconnect(false); } socket.Close(); } throw ex; } } catch (System.Exception ex) { throw ex; } }