public BaseInOut() { if (!IsConnect) { IsConnect = Connect() == 0; if (!IsConnect) { ConnectFailEvent?.Invoke("设备连接失败"); ConnectSuccess = false; } } }
/// <summary> /// 启动客户端 /// </summary> public override void Run() { try { this.NamedPipeClientStream = new NamedPipeClientStream(".", this.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough); this.NamedPipeClientStream.Connect(200); this.NamedPipeClientStream.ReadMode = PipeTransmissionMode.Message; this.NamedPipeClientStream.BeginRead(data, 0, data.Length, new AsyncCallback(PipeReadCallback), this.NamedPipeClientStream); } catch { ConnectFailEvent?.Invoke(); } }
/// <summary> /// 接收数据的回调函数 /// </summary> /// <param name="ar"></param> private void PipeReadCallback(IAsyncResult ar) { this.NamedPipeClientStream = (NamedPipeClientStream)ar.AsyncState; var count = this.NamedPipeClientStream.EndRead(ar); if (count > 0) { string message = encoding.GetString(data, 0, count); NewMessageEvent?.Invoke(message); //简化调用方式 等同于if(NewMessageEvent != Null) {NewMessageEvent(message)} this.NamedPipeClientStream.BeginRead(data, 0, data.Length, new AsyncCallback(PipeReadCallback), this.NamedPipeClientStream); } else if (count == 0) { ConnectFailEvent?.Invoke(); } }