private static void Read(IAsyncResult ar) { try { var offset = 0; var rxbytes = stream.EndRead(ar); if (rxbytes > 0) { stream.BeginRead(tcpdata, 0, tcpdata.Length, Read, null); LogHelper.Log("TcpClient Recv: [" + LogHelper.Logdata(tcpdata, offset, rxbytes - offset) + "]"); TcpServerHelper.Write(tcpdata, offset, rxbytes - offset); SerialPortHelper.Write(tcpdata, offset, rxbytes - offset); } if (rxbytes == 0) { LogHelper.Log("TcpClient Client closed"); OnConnectClosed(); } } catch (Exception e) { if (e is ObjectDisposedException) { LogHelper.Log("TcpClient Connection closed"); } else if (e is IOException && e.Message.Contains("closed")) { LogHelper.Log("TcpClient Connection closed"); } else { LogHelper.Log("TcpClient Exception: " + e.Message); } OnConnectClosed(); } }
/// <summary> /// 接收到消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { Dictionary <string, object> json = Get_payload(e.ApplicationMessage.Payload); string topic = e.ApplicationMessage.Topic; string data = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); LogHelper.Log("mqtt recv:topic: " + e.ApplicationMessage.Topic.ToString() + " payload: " + data); Regex r_subtopic = new Regex(subtopic); // 定义一个Regex对象实例 Match m_subtopic = r_subtopic.Match(e.ApplicationMessage.Topic); // 在字符串中匹配 if (m_subtopic.Success) { SerialPortHelper.Write(e.ApplicationMessage.Payload, 0, e.ApplicationMessage.Payload.Length); } if (topic.IndexOf("$dg/device/" + username + "/" + dtuAddr) == 0) { if (json.ContainsKey("cmd")) { if (json["cmd"].ToString() == "opc_items") { OPCDAHelper.Readitems(json); } else if (json["cmd"].ToString() == "opc_report") { OPCDAHelper.Publishvalues(json); } else if (json["cmd"].ToString() == "printer") { PrinterHelper.PrintPage(json["data"].ToString()); } } } AccessHelper.Do_mdb(topic, json, clientid); MqttServerHelper.Write(e.ApplicationMessage); }