開始運行 監聽 處理事件 ...
private TcpListener _listener;
#region 初始化 listener public override void Init() { try { DevInfo.Read(); var localaddr = IPAddress.Parse(Ip); var port = Convert.ToInt32(port); _listener = new TcpListener(localaddr, port); } finally { StatusChangedEvent?.Invoke(Status); } } #endregion
開始運行
public override void Start() { Init(); _listener?.Start(); Task.Factory.StartNew(MonitTcpClientConnect); }
監聽
private void MonitTcpClientConnect() { while (true) { try { var client = _listener.AcceptTcpClient(); Task.Factory.StartNew(MonitorRecvData, client); } catch { _listener.Stop(); _listener = null; return; } } }
處理事件
private void MonitorRecvData(object obj) { try { var tcpClient = obj as TcpClient; if (tcpClient == null) { return; } var buffer = new byte[1024];var stream = tcpClient.GetStream(); while (true) { var count = stream.Read(buffer, 0, buffer.Length); if (count == 0) { throw new Exception("客戶端下線"); } var str = Encoding.ASCII.GetString(buffer, 0, count); } } catch { // ignored } }