public void WireUp <T>(string text, Func <T> toMessage) { WireUp(text, () => { var args = new MessageRequestArgs(events => events.SendMessage(toMessage())); RaiseEvent(args); }); }
void Run(object obj) { var server = obj as Socket; if (server != null) { #region SocketConnected SocketConnected?.Invoke(this, new SocketEventArgs(server)); #endregion var lstResponse = new List <byte>(); var prev = DateTime.Now; var chr = new Chattering() { ChatteringTime = DisconnectCheckTime }; var bDLE = false; var bValid = false; var IsThStart = true; chr.StateChanged += (o, s) => { if (!s.Value) { IsThStart = false; } }; while (IsThStart) { try { #region DataRead while (server.Available > 0) { try { int n = server.Receive(baResponse); for (int i = 0; i < n; i++) { var d = baResponse[i]; var v = d; if (bDLE) { bDLE = false; if (v >= 0x10) { v -= 0x10; } else { bValid = false; } } switch (d) { #region STX case 0x02: lstResponse.Clear(); bValid = true; break; #endregion #region ETX case 0x03: { if (bValid) { if (lstResponse.Count >= 3) { var sum = (byte)(lstResponse.GetRange(0, lstResponse.Count - 1).Select(x => (int)x).Sum() & 0xFF); if (sum == lstResponse[lstResponse.Count - 1]) { byte slave = lstResponse[0]; byte cmd = lstResponse[1]; string msg = MessageEncoding.GetString(lstResponse.ToArray(), 2, lstResponse.Count - 3); if (MessageRequest != null) { var args = new MessageRequestArgs(slave, cmd, msg); MessageRequest.Invoke(this, args); if (!string.IsNullOrEmpty(args.ResponseMessage)) { server.Send(TextComm.MakePacket(MessageEncoding, slave, cmd, args.ResponseMessage)); } } } } } bValid = false; bDLE = false; lstResponse.Clear(); } break; #endregion #region DLE case 0x10: bDLE = true; break; #endregion #region Default default: lstResponse.Add(v); break; #endregion } } } catch (TimeoutException) { } prev = DateTime.Now; } #endregion #region Buffer Clear if ((DateTime.Now - prev).TotalMilliseconds >= 50 && lstResponse.Count > 0) { lstResponse.Clear(); } #endregion chr.Set(NetworkTool.IsSocketConnected(server)); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.TimedOut) { } else if (ex.SocketErrorCode == SocketError.ConnectionReset) { } else if (ex.SocketErrorCode == SocketError.ConnectionAborted) { IsThStart = false; } } catch { } Thread.Sleep(10); } #region Socket Closed if (server.Connected) { server.Close(); } SocketDisconnected?.Invoke(this, new SocketEventArgs(server)); #endregion } }