internal void Start() { if (-1 == _port) { return; } try { IPAddress addr = IPAddress.Loopback; _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); #if (DEBUG) // Check an option that provides for listening on all the network interfaces, not only loopback (DEBUG builds only) if (!Core.SettingStore.ReadBool("RemoteControl", "LoopbackInterfaceOnly", true)) { addr = IPAddress.Any; } #endif if (_port != 0) { _listenSocket.Bind(new IPEndPoint(addr, _port)); } else { _storePort = true; while (true) { _port = generateRandomPort(); try { _listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, _port)); break; } catch (SocketException ex) { if (ex.ErrorCode != 10048) // WSAEADDRINUSE { return; } } } } _listenSocket.Listen((int)SocketOptionName.MaxConnections); _stop = Winsock.WSACreateEvent(); Winsock.WSAResetEvent(_stop); _mainThread = new Thread(new ThreadStart(Listener)); _mainThread.Name = _threadName; _mainThread.Start(); _mainThread.Priority = ThreadPriority.BelowNormal; } catch { Winsock.WSASetEvent(_stop); _port = -1; throw; } return; }
internal void Stop() { if (Winsock.WSAWaitForMultipleEvents(1, new IntPtr[] { _stop }, 1 /*true*/, 0, 0 /*false*/) == Winsock.WSA_WAIT_EVENT_0) { Trace.WriteLine("[RCS] Second call to Stop()."); return; } Winsock.WSASetEvent(_stop); Trace.WriteLine("[RCS] Stop event has been fired."); try { Trace.WriteLine("[RCS] Waiting for server thread..."); if (!Application.MessageLoop) { _mainThread.Join(); } else { while (_mainThread.IsAlive && !_mainThread.Join(100)) { Application.DoEvents(); } } Trace.WriteLine("[RCS] Server thread has finished."); } catch (Exception ex) { Trace.WriteLine("[RCS] Server thread waiting exception: " + ex.Message); } finally { _mainThread = null; } Winsock.WSACloseEvent(_stop); }