private void CheckForThreadsToPurge() { ArrayList deleteList = new ArrayList(); // Check for any clients SocketListeners that are to be // deleted and put them in a separate list in a thread safe fashion. lock (m_socketListenersList) { foreach (TCPSocketListener socketListener in m_socketListenersList) { if (socketListener.IsMarkedForDeletion()) { ORTLog.LogD(string.Format("PurgingThread: StopSocketListener {0}", socketListener.ToString())); deleteList.Add(socketListener); socketListener.StopSocketListener(); } } // Delete all the client SocketConnection ojects which are // in marked for deletion and are in the delete list. for (int i = 0; i < deleteList.Count; ++i) { m_socketListenersList.Remove(deleteList[i]); } } deleteList = null; }
protected override void OnStart(string[] args) { var appSettings = ConfigurationManager.AppSettings; var LogFlags = ConfigurationManager.GetSection("LogFlags") as NameValueCollection; string debugFilename = @"C:\cygwin64\home\listdog\logs\ort_debug.txt"; string sessionFilename = @"C:\cygwin64\home\listdog\logs\ort_session.txt"; if (LogFlags != null) { if (LogFlags["LogDebug"] != null && string.Compare(LogFlags["LogDebug"].ToString(), "1", true) == 0) { ORTLog.EnableDebug = true; } if (LogFlags["LogSession"] != null && string.Compare(LogFlags["LogSession"].ToString(), "1", true) == 0) { ORTLog.EnableSession = true; } if (LogFlags["DebugFilename"] != null) { debugFilename = LogFlags["DebugFilename"].ToString(); } if (LogFlags["SessionFilename"] != null) { sessionFilename = LogFlags["SessionFilename"].ToString(); } } ORTLog.Open(debugFilename, sessionFilename); var TcpFlags = ConfigurationManager.GetSection("LogFlags") as NameValueCollection; int deviceServerPort = 3333; int commandServerPort = 8888; if (TcpFlags != null) { if (TcpFlags["ORTDeviceServerPort"] != null) { deviceServerPort = int.Parse(TcpFlags["ORTDeviceServerPort"].ToString()); } if (TcpFlags["ORTCommandServerPort"] != null) { commandServerPort = int.Parse(TcpFlags["ORTCommandServerPort"].ToString()); } } ORTLog.LogD("Service Started"); m_deviceServer = new DeviceServer(IPAddress.Any, deviceServerPort); m_deviceServer.StartServer(); m_commandServer = new CommandServer(IPAddress.Any, commandServerPort); m_commandServer.StartServer(); }
protected override void OnStop() { m_deviceServer.StopServer(); m_deviceServer = null; m_commandServer.StopServer(); m_commandServer = null; ORTLog.LogD("Service Stopped"); ORTLog.Close(); }
public static bool Add(string key, DeviceListener s) { try { return(DeviceListeners.TryAdd(key, s)); } catch (Exception e) { ORTLog.LogS(string.Format("SharedMem Exception in Add {0}", e.ToString())); return(false); } }
public static bool Remove(string key) { DeviceListener s; try { return(DeviceListeners.TryRemove(key, out s)); } catch (Exception e) { ORTLog.LogS(string.Format("SharedMem Exception in Remove {0}", e.ToString())); return(false); } }
public int Send(byte[] buffer) { int ret = 0; try { ret = m_clientSocket.Send(buffer); } catch (Exception e) { ORTLog.LogS(string.Format("ORTDevice Exception in Send {0}", e.ToString())); } return(ret); }
/// <summary> /// Thread method for purging Client Listeneres that are marked for /// deletion (i.e. clients with socket connection closed). This thead /// is a low priority thread and sleeps for 10 seconds and then check /// for any client SocketConnection obects which are obselete and /// marked for deletion. /// </summary> private void PurgingThreadStart() { ORTLog.LogD("PurgingThread: Start"); while (!m_stopPurging) { CheckForThreadsToPurge(); // Wait 10 seconds, but check for shutdown every 100ms int sleep = 10000; while (!m_stopPurging && sleep > 0) { Thread.Sleep(100); sleep -= 100; } } ORTLog.LogD("PurgingThread: Stop"); }
protected override void ServerThreadStart() { Socket clientSocket = null; TCPSocketListener socketListener = null; while (!m_stopServer) { try { clientSocket = m_server.AcceptSocket(); } catch (Exception) { // This happens when we shutdown the servive continue; } try { ORTLog.LogS(String.Format("ORTCommand: Connection made {0}", clientSocket.RemoteEndPoint)); } catch (Exception e) { ORTLog.LogS(string.Format("ORTCommand Exception {0}", e.ToString())); continue; } // Create a SocketListener object for the client. socketListener = new CommandListener(clientSocket); // Add the socket listener to an array list in a thread safe fashion. lock (m_socketListenersList) { m_socketListenersList.Add(socketListener); } // Start communicating with the client in a different thread. socketListener.StartSocketListener(); } }
public void StartSocketListener() { if (m_clientSocket == null) { m_markedForDeletion = true; return; } try { m_remoteEndPoint = m_clientSocket.RemoteEndPoint.ToString(); } catch (Exception e) { ORTLog.LogS(string.Format("TCPSocketListener Exception {0}", e.ToString())); m_markedForDeletion = true; return; } m_clientListenerThread = new Thread(new ThreadStart(SocketListenerThreadStart)); m_clientListenerThread.Start(); }
protected override void SocketListenerThreadStart() { int size = 0; Byte[] byteBuffer = new Byte[1024]; try { m_clientSocket.ReceiveTimeout = 500; } catch (Exception) { } while (!m_stopClient) { try { size = m_clientSocket.Receive(byteBuffer); if (size == 0) { // Indicates the remote side closed the connection break; } } catch (SocketException e) { if (e.ErrorCode == WSAETIMEDOUT) { // Timeout while waiting for shutdown continue; } else { ORTLog.LogS(string.Format("ORTCommand Exception in Receive {0}", e.ToString())); break; } } catch (Exception e) { ORTLog.LogS(string.Format("ORTCommand Exception in Receive {0}", e.ToString())); break; } // Get a string representation from the socket buffer string data = Encoding.ASCII.GetString(byteBuffer, 0, size); if (!IsValidIpsData(data)) { ORTLog.LogS(String.Format("ORTCommand: Invalid data={0}", CleanString(data))); break; } string customer = ""; string device = ""; string command = ""; try { // Parse the customer+device customer = data.Split(null)[1]; device = data.Split(null)[2]; // Parse the command - hacky :/ int i = data.IndexOf(" ", data.IndexOf(" ", data.IndexOf(" ") + 1) + 1) + 1; command = data.Substring(i); // Remove the carriage return and/or line feed command = Regex.Replace(command, @"\r\n?|\n", ""); } catch (Exception) { ORTLog.LogS(String.Format("ORTCommand: Invalid data={0}", CleanString(data))); break; } ORTLog.LogS(string.Format("ORTCommand: customer={0} device={1} command={2}", customer, device, command)); string key = GetKey(customer, device); // Get the cooresponding socket and send the command DeviceListener d = SharedMem.Get(key); if (d != null) { try { if (d.Send(Encoding.ASCII.GetBytes(command)) == 0) { break; } } catch (Exception e) { ORTLog.LogS(string.Format("ORTCommand Exception {0}", e.ToString())); break; } } else { ORTLog.LogS(string.Format("ORTCommand: customer device combination not found: {0}", key)); } } ORTLog.LogS(String.Format("ORTCommand: Connection dropped {0}", this.ToString())); try { m_clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } m_clientSocket.Close(); m_markedForDeletion = true; }
protected override void SocketListenerThreadStart() { Byte[] byteBuffer = new Byte[1024]; int size = 0; try { size = m_clientSocket.Receive(byteBuffer); } catch (Exception e) { ORTLog.LogS(string.Format("ORTDevice Exception in Receive {0}", e.ToString())); m_clientSocket.Close(); m_markedForDeletion = true; return; } string data = Encoding.ASCII.GetString(byteBuffer, 0, size); if (!IsValidIpsData(data)) { ORTLog.LogS(String.Format("ORTDevice: Invalid data={0}", CleanString(data))); ORTLog.LogS(String.Format("ORTDevice: Connection dropped {0}", this.ToString())); try { m_clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } m_clientSocket.Close(); m_markedForDeletion = true; return; } string customer = ""; string device = ""; string ipAddr = ""; try { // Parse the customer+device customer = data.Split(null)[1]; device = data.Split(null)[2]; ipAddr = data.Split(null)[3]; } catch (Exception) { ORTLog.LogS(String.Format("ORTDevice: Invalid data={0}", CleanString(data))); ORTLog.LogS(String.Format("ORTDevice: Connection dropped {0}", this.ToString())); try { m_clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } m_clientSocket.Close(); m_markedForDeletion = true; return; } string key = GetKey(customer, device); // Check if this key already exists DeviceListener d = SharedMem.Get(key); if (d != null) { // Detected duplicate ORTLog.LogS(String.Format("ORTDevice: Detected duplicate customer={0} device={1}", customer, device)); // Remove existing key ORTLog.LogS(String.Format("ORTDevice: Remove listener for customer={0} device={1}", customer, device)); SharedMem.Remove(key); // Shutdown the existing (zombie) listener d.StopSocketListener(); } ORTLog.LogS(String.Format("ORTDevice: Add listener for customer={0} device={1} localIpAddr={2}", customer, device, ipAddr)); if (!SharedMem.Add(key, this)) { ORTLog.LogS(String.Format("ORTDevice: Unable to add key={0}", key)); ORTLog.LogS(String.Format("ORTDevice: Connection dropped {0}", this.ToString())); try { m_clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } m_clientSocket.Close(); m_markedForDeletion = true; return; } // Block forever waiting for the connection to terminate while (!m_stopClient) { bool poll = false; try { poll = m_clientSocket.Poll(100000, SelectMode.SelectRead); // 100ms } catch (Exception e) { ORTLog.LogS(string.Format("ORTDevice Exception in Poll {0}", e.ToString())); break; } if (poll) { // Connection has been closed, reset, or terminated break; } } if (SharedMem.Remove(key)) { ORTLog.LogS(String.Format("ORTDevice: Removed listener for customer={0} device={1}", customer, device)); } ORTLog.LogS(String.Format("ORTDevice: Connection dropped {0}", this.ToString())); try { m_clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } m_clientSocket.Close(); m_markedForDeletion = true; }