private void AsyncRecvMsg(IAsyncResult ar) { RecvMsgEventArgs args = (RecvMsgEventArgs)ar.AsyncState; args.RecvBytes.Clear(); args.Message = ""; try { if (_clientStream.CanRead) { // CanRead为false,说明m_clientStream流不可读,可能是m_clientStream流已关闭或发生错误,退出本次读取处理 // 为true,则说明m_clientStream流可读,可继续执行后续代码 int bytesRead = _clientStream.EndRead(ar); // 读取缓冲区大小为256字节,用于OBD诊断命令已足够,无需使用NetworkStream.DataAvailable属性 // 来判断是否还有数据没有读取完,需要分段多次读取 for (int i = 0; i < bytesRead; i++) { args.RecvBytes.Add(_recvBuf[i]); } args.Message += Encoding.UTF8.GetString(_recvBuf, 0, bytesRead); // 继续准备读取可能会传进来的数据 _clientStream.BeginRead(_recvBuf, 0, BUF_SIZE, AsyncRecvMsg, args); } } catch (Exception ex) { _log.TraceError(ex.Message); Close(); } finally { RecvedMsg?.Invoke(this, args); } }
private void OnRecvedMsg(object sender, RecvMsgEventArgs e) { foreach (byte item in e.RecvBytes) { OnRxChar(item); } }
public void ConnectServer() { try { _client = new TcpClient(_strHostName, _iPort); _clientStream = _client.GetStream(); _recvBuf = new byte[BUF_SIZE]; RecvMsgEventArgs args = new RecvMsgEventArgs(); _clientStream.BeginRead(_recvBuf, 0, BUF_SIZE, AsyncRecvMsg, args); } catch (Exception) { Close(); throw; } }