/// <summary> /// Creates a socket client object and subscribes to events for /// connect, disconnet and data receive /// </summary> /// <returns>Socket client object</returns> private SocketClient createSocketClient() { SocketClient client = null; if (ServerAddress != null && ServerPort >= 0) { System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(ServerAddress); client = new SocketClient(ipaddress, ServerPort); client.OnClientDataReceived += _socketClient_OnClientDataReceived; client.OnClientConnected += _socketClient_OnClientConnected; client.OnClientConnectionClosed += _socketClient_OnClientConnectionClosed; } return client; }
/// <summary> /// Uninitialize. Stop socket server /// </summary> /// <returns>true</returns> private void unInit() { if (socketClient != null) { socketClient.Dispose(); socketClient = null; } }
/// <summary> /// Thread proc which tries to connect to the tcpip server. If it cannot /// connect, it sleeps for sometime and retries /// </summary> private void connectProc() { while (!_quitConnect) { try { Log.Debug("Trying to connecting to tcp/ip server"); if (socketClient == null) { socketClient = createSocketClient(); } if (socketClient != null) { if (!socketClient.Connect()) { Log.Debug("Tcp/ip server not detected. Will retry..."); Thread.Sleep(waitInterval); } else { Log.Debug("Successfully connected to tcp/ip server"); _evtConnectRetry.WaitOne(); _evtConnectRetry.Reset(); } } else { Thread.Sleep(waitInterval); } } catch (Exception ex) { Log.Debug("Error connecting to server " + ex); } } Log.Debug("Thread exited"); }
/// <summary> /// Closes the client socket. Unsunscribes from events /// </summary> /// <param name="client"></param> private void closeClientSocket(SocketClient client) { if (client == null) { return; } client.OnClientDataReceived -= _socketClient_OnClientDataReceived; client.OnClientConnected -= _socketClient_OnClientConnected; client.OnClientConnectionClosed -= _socketClient_OnClientConnectionClosed; }
/// <summary> /// Event handler invoked when socket client disconnects. /// </summary> /// <param name="addr">Address of the tcp/ip server</param> private void _socketClient_OnClientConnectionClosed(System.Net.IPAddress addr) { Log.Debug("Disconnected from " + addr); closeClientSocket(socketClient); socketClient = null; _evtConnectRetry.Set(); onDisconnected(addr); }
/// <summary> /// Initializes a new instance of the class. /// </summary> public WinsockClientActuatorBase() { socketClient = null; }