public override int GetHashCode() { return(GlobalMaxConnections + GlobalMaxDownloadSpeed + GlobalMaxHalfOpenConnections + GlobalMaxUploadSpeed + ListenPort.GetHashCode() + AllowedEncryption.GetHashCode() + SaveFolder.GetHashCode()); }
public override int GetHashCode() { return(MaximumConnections + MaximumDownloadSpeed + MaximumUploadSpeed + MaximumHalfOpenConnections + ListenPort.GetHashCode() + AllowedEncryption.GetHashCode() + CacheDirectory.GetHashCode()); }
public void Start() { IPEndPoint endpoint = new IPEndPoint(0, ListenPort); _listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(endpoint); _listenSocket.Listen(100); trace.Info("Listening on {0}:{1}", endpoint.Address.ToString(), ListenPort.ToString()); StartAccept(_acceptSocketAsyncEventArgs); }
public void ClosePort() { try { ListenPort.Close(); Debug.WriteLine("串口状态:" + (ListenPort.IsOpen ? "Open" : "Closed")); } catch (Exception exp) { Debug.WriteLine("[GSM] Model " + exp.Message); } }
public Monitor(string name) : base(HooserProtocolPort, HooserProtocolPort, name) { Debug.WriteLine( "ServiceMonitor listening on port " + ListenPort.ToString()); HoosierMessageBytes = new HoosierMessage(Name).GetBytes(); #if ENABLE_RECEIVE_HANDLER ReceiveMessage += new ReceiveMessageDelegate(ReceiveEventHandler); #endif }
protected void MonitorThreadBody() { // listen for more requests Debug.WriteLine("Hoosier.MonitorThreadBody listening on " + Address.ToString() + ":" + ListenPort.ToString()); try { Listener = new UdpClient(ListenPort); #if !MASTER_CONTROLLER Listener.EnableBroadcast = true; // listener.ExclusiveAddressUse = false; Listener.MulticastLoopback = false; #endif Debug.WriteLine("Hoosier.MonitorThreadBody sending StartupMessage"); SendStartupMessage(); while (!Done) { IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, ListenPort); Debug.WriteLine("Hoosier.MonitorThreadBody Listener.Receive..."); byte[] bytes = Listener.Receive(ref groupEP); Debug.WriteLine("Hoosier.MonitorThreadBody received " + bytes.Length.ToString() + " bytes"); if (IgnoreLoopback && Address.Equals(groupEP.Address)) { //Debug.WriteLine( "\t\tIgnoring loopback" ); continue; } if (ReceiveMessage != null) { Message msg = Message.Decode(bytes); ReceiveMessage(msg, groupEP); } } } catch (Exception e) { Debug.WriteLine("Hoosier.MonitorThreadBody Exception: " + e.Message); } Debug.WriteLine("Hoosier.MonitorThreadBody Exits "); }
public Provider(string name) : base(HooserProtocolPort, HooserProtocolPort, name) { Debug.WriteLine( "Provider " + name + " listening on port " + ListenPort.ToString()); HowdyMessageBytes = new HowdyMessage(Name).GetBytes(); GoodbyeMessageBytes = new GoodbyeMessage(Name).GetBytes(); ReceiveMessage += new ReceiveMessageDelegate(ReceiveEventHandler); }
public bool OpenPort() { try { ListenPort.Open(); Debug.WriteLine("串口状态:" + (ListenPort.IsOpen ? "Open" : "Closed")); InvokeMessage(String.Format("开启串口{0}成功", ListenPort.PortName), "初始化"); return(true); } catch (Exception exp) { //InvokeMessage("串口" + ListenPort.PortName + "打开失败!", "初始化"); InvokeMessage(String.Format("开启串口{0}失败", ListenPort.PortName), "初始化"); Debug.WriteLine("[GSM] Model " + exp.Message); } return(false); }
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { int n = ListenPort.BytesToRead; byte[] buf = new byte[n]; ListenPort.Read(buf, 0, n); m_inputBuffer.AddRange(buf); //获取结束符号的位置 var count = (from r in m_inputBuffer where (r == 59) select r).Count(); Debug.WriteLine(count + " ----- " + Encoding.ASCII.GetString(buf)); string tmp = Encoding.ASCII.GetString(m_inputBuffer.ToArray <byte>()); WriteToFileClass writeClass = new WriteToFileClass("ReceivedLog"); Thread t = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile)); t.Start("GPRS: " + "长度:" + tmp.Length + " " + tmp + "\r\n"); if (tmp.Contains("$")) { string data = Encoding.ASCII.GetString(m_inputBuffer.ToArray <byte>()); //判定短信接收的标志符号 if (data.Contains("CMT")) { if (data.EndsWith("\r\n")) { string[] a = new string[] { "CMT" }; //按CMT划分字符串 string[] ArrData = data.Split(a, StringSplitOptions.None); for (int i = 1; i < ArrData.Count(); i++) { //增加一层调用,支持多线程 Thread t1 = new Thread(new ParameterizedThreadStart(parse_Updata)); t1.Start(ArrData[i]); } //如果判定到结束符号,则清空缓冲区 m_inputBuffer.Clear(); } } } }
public bool Start() { try { _Listener.SendTimeout = _SendTimeout; _Listener.ReceiveTimeout = _ReceiveTimeout; _Listener.Listen(10); _IsListening = true; _Log.Write(LogType.Warning, "=================== Server Socket Start to Listen At " + LocalIP + ":" + ListenPort.ToString() + "===============\r\n", true); _Listener.BeginAccept(new AsyncCallback(OnClientConnect), null); return(true); } catch (Exception ex) { _IsListening = false; _Log.Write(ex); return(false); } }
private void SendMsg_Thead(object obj) { var gsmStruct = obj as GsmMsgStruct; if (null == gsmStruct) { return; } string phone = gsmStruct.Phone; string msg = gsmStruct.Msg; ListenPort.ReadTimeout = 60000; string returnMsg = string.Empty; try { //注销事件关联,为发送做准备 ListenPort.DataReceived -= Port_DataReceived; ListenPort.Write("AT+CMGS=" + phone + "\r"); ListenPort.ReadTo(">"); ListenPort.Write(msg + (char)(26)); ListenPort.DiscardInBuffer(); string wirteMessage = "AT+CMGS=" + phone + "\r" + ">" + msg + (char)(26); InvokeMessage(wirteMessage, "发送"); string temp = string.Empty; while (!temp.Trim().Contains("OK") && !temp.Trim().Contains("ERROR")) { Debug.WriteLine("temp = " + temp); temp = ListenPort.ReadLine(); returnMsg += temp; } Debug.WriteLine("result = " + returnMsg); if (returnMsg.Contains(msg + (char)(26))) { returnMsg = returnMsg.Replace((msg + (char)(26)), string.Empty); } InvokeMessage(returnMsg, "接收"); IsCommonWorkNormal = true; } catch (TimeoutException exp) { IsCommonWorkNormal = false; if (null != GSMTimeOut) { GSMTimeOut(this, new ReceivedTimeOutEventArgs() { Second = ListenPort.ReadTimeout / 1000 }); } InvokeMessage("短信接收超时", "接收"); Debug.WriteLine("短信接收失败"); } catch (Exception exp) { IsCommonWorkNormal = false; InvokeMessage("短信接收失败", "接收"); if (null != GSMTimeOut) { GSMTimeOut(this, new ReceivedTimeOutEventArgs() { Second = ListenPort.ReadTimeout / 1000 }); } Debug.WriteLine("短信接收失败"); } finally { //事件重新绑定 正常监视串口数据 ListenPort.DataReceived += Port_DataReceived; } // GSM通讯口状态监测 if (SerialPortStateChanged != null) { SerialPortStateChanged(this, new CEventSingleArgs <CSerialPortState>(new CSerialPortState() { PortNumber = Int32.Parse(ListenPort.PortName.Replace("COM", "")), BNormal = IsCommonWorkNormal, PortType = m_portType })); } }
/// <summary> /// 发送AT指令 逐条发送AT指令 调用一次发送一条指令 /// 能返回一个OK或ERROR算一条指令 /// </summary> /// <param name="ATCom">AT指令</param> /// <returns>发送指令后返回的字符串</returns> public string SendMsg(string atCom, out bool isSendSuccesse) { isSendSuccesse = false; ListenPort.ReadTimeout = 3000; string result = string.Empty; //忽略接收缓冲区内容,准备发送 ListenPort.DiscardInBuffer(); //注销事件关联,为发送做准备 ListenPort.DataReceived -= Port_DataReceived; try { /* 写入指令 */ ListenPort.Write(atCom + "\r"); /* 接收数据 循环读取数据 直至收到“OK”或“ERROR”*/ string temp = string.Empty; if (!atCom.Contains(GsmHelper.AT_SAVE)) { while (!temp.Trim().Contains("OK") && !temp.Trim().Contains("ERROR")) { temp = ListenPort.ReadLine(); result += temp; } Debug.WriteLine(result); } else { var str = ListenPort.ReadExisting(); //while (str.Length != 9) //{ // str += ListenPort.ReadExisting(); //} result = str; } /* 如果缓冲区中包含已发送的指令,则清除 */ if (result.Contains(atCom)) { result = result.Replace(atCom, string.Empty); } isSendSuccesse = true; } catch (TimeoutException exp) { isSendSuccesse = false; //InvokeMessage("设置参" + atCom + "超时", "接收"); if (null != GSMTimeOut) { GSMTimeOut(this, new ReceivedTimeOutEventArgs() { Second = ListenPort.ReadTimeout / 1000 }); } } catch (Exception exp) { isSendSuccesse = false; Debug.WriteLine(String.Format("发送指令:{0} 错误\r{1}", atCom, exp.Message)); } finally { //事件重新绑定 正常监视串口数据 ListenPort.DataReceived += Port_DataReceived; } return(result); }
private void Port_DataReceived_old(object sender, SerialDataReceivedEventArgs e) { int n = ListenPort.BytesToRead; byte[] buf = new byte[n]; ListenPort.Read(buf, 0, n); m_inputBuffer.AddRange(buf); var count = (from r in m_inputBuffer where (r == 59) select r).Count(); Debug.WriteLine(count + " ----- " + Encoding.ASCII.GetString(buf)); string flag = Encoding.ASCII.GetString(m_inputBuffer.ToArray <byte>()); if (flag.Contains("$")) { string data = Encoding.ASCII.GetString(m_inputBuffer.ToArray <byte>()); if (data.Contains("CMT")) { if (data.EndsWith(";")) { string[] a = new string[] { "CMT" }; string[] ArrData = data.Split(a, StringSplitOptions.None); for (int i = 1; i < ArrData.Count(); i++) { Thread t = new Thread(new ParameterizedThreadStart(parse_Updata)); t.Start(ArrData[i]); Debug.WriteLine(ArrData[i]); InvokeMessage(ArrData[i], "GSM接收:"); m_inputBuffer.Clear(); } } } //} } else { // string data = Encoding.ASCII.GetString(m_inputBuffer.ToArray<byte>()).Replace("\n", "").Replace("\t", "").Replace("\r", ""); string data = Encoding.ASCII.GetString(m_inputBuffer.ToArray <byte>()); if (data.Contains("CMT") && data.Contains("1G")) { string data_1 = data.Substring(data.IndexOf("1G")); if (data_1.EndsWith("\r\n")) { string[] a = new string[] { "CMT" }; string[] ArrData = data.Split(a, StringSplitOptions.None); for (int i = 1; i < ArrData.Count(); i++) { Thread t = new Thread(new ParameterizedThreadStart(Parser_2)); t.Start(ArrData[i]); // Parser_2(ArrData[i]); Debug.WriteLine(ArrData[i]); m_inputBuffer.Clear(); } } } else if (data.Contains("CMT") && data.Contains("TRU")) { string data_1 = data.Substring(data.IndexOf("TRU")); if (data_1.EndsWith("\r\n")) { string[] a = new string[] { "CMT" }; string[] ArrData = data.Split(a, StringSplitOptions.None); for (int i = 1; i < ArrData.Count(); i++) { Thread t = new Thread(new ParameterizedThreadStart(Parser_2)); t.Start(ArrData[i]); // Parser_2(ArrData[i]); Debug.WriteLine(ArrData[i]); m_inputBuffer.Clear(); } } } else if (data.Contains("CMT") && data.Contains("\r\n")) { if (data.EndsWith("\r\n")) { InvokeMessage(data, "接收"); m_inputBuffer.Clear(); } } } }
public new void Load() { // Try to load, and save a new file if load failed if (!base.Load()) { base.Save(); } RMLog.Level = LogLevel; // Output the settings being used RMLog.Info("Using settings from " + base.FileName); RMLog.Info("-Listen port...." + ListenPort.ToString()); if (TargetPort > 0) { RMLog.Info("-Telnet target.." + TargetHostname + ":" + TargetPort.ToString()); } else { RMLog.Info("-Telnet target..DISABLED"); } if (RLoginPort > 0) { RMLog.Info("-RLogin target.." + TargetHostname + ":" + RLoginPort.ToString()); } else { RMLog.Info("-RLogin target..DISABLED"); } RMLog.Info("-Log level......" + LogLevel.ToString()); if (CertificateFilename != "") { // If file doesn't exist, and it's relative, convert to absolute if (!File.Exists(CertificateFilename) && !Path.IsPathRooted(CertificateFilename)) { CertificateFilename = StringUtils.PathCombine(ProcessUtils.StartupPath, CertificateFilename); } if (File.Exists(CertificateFilename)) { RMLog.Info("-Cert file......" + CertificateFilename); if (CertificatePassword == "") { RMLog.Info("-Cert password..none"); } else { RMLog.Info("-Cert password..yes (hidden)"); } } else { RMLog.Error("-Cert file not found: '" + CertificateFilename + "'"); CertificateFilename = ""; } } if (RelayFilename != "") { // If file doesn't exist, and it's relative, convert to absolute if (!File.Exists(RelayFilename) && !Path.IsPathRooted(RelayFilename)) { RelayFilename = StringUtils.PathCombine(ProcessUtils.StartupPath, RelayFilename); } if (File.Exists(RelayFilename)) { RMLog.Info("-Relay file....." + RelayFilename); } else { RMLog.Error("-Relay file not found: '" + RelayFilename + "'"); RelayFilename = ""; } } }
/// <summary> /// Method run as a thread to receive Client messages. /// </summary> public void ServerHandler() { // Initialize variables string msg = string.Empty; string messageToSend = string.Empty; string msgFiltered = string.Empty; byte[] buffer = new byte[2048]; Socket serverSocket = null; Stopwatch swHeartBeat = new Stopwatch(); Connected = false; OnServerConnected(Connected); ASCIIEncoding asen = new ASCIIEncoding(); // Initializes the Listener TcpListener listener = new TcpListener(IPAddress.Any, Convert.ToInt32(ListenPort)); this.Running = true; string sendString = string.Empty; while (!this.ServerStopped) { try { // Start listening for incomming messages. listener.Start(); string str = Convert.ToString(ClientIPaddress) + ":" + ListenPort; OnServerStatusMessageUpdate(this.Name + ": Server waiting for connection from: " + str); Connected = false; OnServerConnected(Connected); // Wait for connection while (!listener.Pending() && !ServerStopped) { Thread.Sleep(10); } if (ServerStopped) { continue; } serverSocket = listener.AcceptSocket(); // Debug code block to catch possible conflict IPEndPoint ep = (IPEndPoint)serverSocket.LocalEndPoint; if (ep.Port != this.ListenPort) { OnServerTCP_MessageUpdate("Local End Point:" + ep.Port.ToString() + " Listen Port:" + ListenPort.ToString()); } OnServerStatusMessageUpdate(this.Name + ": Server connected"); Connected = true; OnServerConnected(Connected); swHeartBeat.Start(); while (serverSocket.Connected && !ServerStopped) { // Init buffer count (number of tokens) int bufferCount = 0; // Poll the socket to check for client message serverSocket.Poll(10000, SelectMode.SelectRead); if (serverSocket.Available > 0) { // Read the TCP/IP line bufferCount = serverSocket.Receive(buffer); for (int i = 0; i < bufferCount; i++) { if (buffer[i] != 10) { sendString = sendString + (char)buffer[i]; } else { // Filter out the non readable characters. msgFiltered = MessageFilter(sendString); OnServerStatusMessageUpdate("<" + this.Name + ": Server recieved:" + msgFiltered); // Fire event and send the message to the subscriber. It is expected for the // subscriber to update the Server.Response property. OnServerTCP_MessageUpdate(sendString); sendString = string.Empty; } } } else { // Process messages in the queue if (serverQ.Count > 0) { // Send message to Client messageToSend = serverQ.Dequeue(); serverSocket.Send(asen.GetBytes(messageToSend)); msgFiltered = MessageFilter(messageToSend); OnServerStatusMessageUpdate(">" + this.Name + ": Server sent: " + msgFiltered); swHeartBeat.Reset(); swHeartBeat.Start(); } if (this.SendHeartbeat) { if (swHeartBeat.ElapsedMilliseconds > this.HeartbeatFrequency * 1000) { messageToSend = "Heartbeat" + this.Terminator; serverSocket.Send(asen.GetBytes(messageToSend)); //OnServerStatusMessageUpdate(">" + this.Name + ": Server sent: " + messageToSend); swHeartBeat.Reset(); swHeartBeat.Start(); } } } if (ServerStopped) { continue; } } } catch (Exception ex) { OnServerStatusMessageUpdate(this.Name + ": Server Exception>" + ex.Message); Thread.Sleep(500); } finally { /* clean up */ if (serverSocket != null) { if (!serverSocket.Connected) { Connected = false; OnServerConnected(Connected); OnServerStatusMessageUpdate(this.Name + ": Server not connected"); } } } } // Clean up when server exits OnServerStatusMessageUpdate(this.Name + ": Server stopped"); Connected = false; OnServerConnected(Connected); this.Running = false; listener.Stop(); if (serverSocket != null) { serverSocket.Shutdown(SocketShutdown.Both); serverSocket.Close(); } }
public void Stop() { _Listener.Close(1000); Clean(); _IsListening = false; _Log.Write(LogType.Warning, "=================== Server Socket Stop to Listen At " + LocalIP + ":" + ListenPort.ToString() + "===============\r\n", true); }
public Socket Accept(Socket listenChan) { lock ( listenChan ) { if (listenChan != null) { Socket newChan = listenChan.Accept( ); if (Channel != null) { Log.w("ddms", "debugger already talking to " + Client.ToString( ) + " on " + ListenPort.ToString( )); newChan.Close( ); return(null); } Channel = newChan; Channel.Blocking = false; ConnectionState = ConnectionStates.AwaitShake; return(Channel); } return(null); } }
public new void Load() { // Try to load, and save a new file if load failed if (!base.Load()) { base.Save(); } RMLog.Level = LogLevel; // Output the settings being used RMLog.Info("Using settings from " + base.FileName); RMLog.Info("-Listen port: " + ListenPort.ToString()); if (TargetPort > 0) { RMLog.Info("-Telnet target: " + TargetHostname + ":" + TargetPort.ToString()); } else { RMLog.Info("-Telnet target: DISABLED"); } if (RLoginPort > 0) { RMLog.Info("-RLogin target: " + TargetHostname + ":" + RLoginPort.ToString()); } else { RMLog.Info("-RLogin target: DISABLED"); } RMLog.Info("-Log level: " + LogLevel.ToString()); if (!string.IsNullOrWhiteSpace(CertificateFilename)) { // If file doesn't exist, and it's relative, convert to absolute if (!File.Exists(CertificateFilename) && !Path.IsPathRooted(CertificateFilename)) { CertificateFilename = StringUtils.PathCombine(ProcessUtils.StartupPath, CertificateFilename); } if (File.Exists(CertificateFilename)) { RMLog.Info("-Cert file: " + CertificateFilename); if (string.IsNullOrWhiteSpace(CertificatePassword)) { RMLog.Info("-Cert password: none"); } else { RMLog.Info("-Cert password: yes (hidden)"); } } else { RMLog.Error("-Cert file not found: '" + CertificateFilename + "'"); CertificateFilename = ""; } } if (!string.IsNullOrWhiteSpace(User) && OSUtils.IsUnix) { RMLog.Info($"-Run as user: '******'"); } if (!string.IsNullOrWhiteSpace(RelayFilename)) { // If file doesn't exist, and it's relative, convert to absolute if (!File.Exists(RelayFilename) && !Path.IsPathRooted(RelayFilename)) { RelayFilename = StringUtils.PathCombine(ProcessUtils.StartupPath, RelayFilename); } if (File.Exists(RelayFilename)) { RMLog.Info("-Relay file: " + RelayFilename); } else { RMLog.Error("-Relay file not found: '" + RelayFilename + "'"); RelayFilename = ""; } } if (!string.IsNullOrWhiteSpace(RelayDeniedFilename)) { // If file doesn't exist, and it's relative, convert to absolute if (!File.Exists(RelayDeniedFilename) && !Path.IsPathRooted(RelayDeniedFilename)) { RelayDeniedFilename = StringUtils.PathCombine(ProcessUtils.StartupPath, RelayDeniedFilename); } if (File.Exists(RelayDeniedFilename)) { RMLog.Info("-Relay denied file: " + RelayDeniedFilename); } else { RMLog.Error("-Relay denied file not found: '" + RelayDeniedFilename + "'"); RelayDeniedFilename = ""; } } if (MaxIdleTimeInMinutes > 0) { RMLog.Info($"-Max idle time before disconnecting: {MaxIdleTimeInMinutes} minutes"); } else { RMLog.Info("-Max idle time before disconnecting: DISABLED"); } if (MaxSessionLengthInHours > 0) { RMLog.Info($"-Max session length before disconnecting: {MaxSessionLengthInHours} hours"); } else { RMLog.Info("-Max session length before disconnecting: DISABLED"); } }