/// <summary> /// 绑定地址监听客户端 /// </summary> public void ServerSck() { try { serverSck.Bind(endPoint); serverSck.Listen(100); //获取客户端连接 Task.Run(() => { while (true) { try { tSocket = serverSck.Accept(); if (tSocket.Connected) { string point = tSocket.RemoteEndPoint.ToString(); NotifyCommandEvent?.Invoke("Connect", $"{point}连接成功"); Task.Factory.StartNew(Recv, tSocket); Thread.Sleep(500); } } catch (Exception ex) { NotifyCommandEvent?.Invoke("Break", $"客户端与服务端连接异常{ex.Message}"); } } }); } catch (Exception ex) { NotifyCommandEvent?.Invoke("Break", $"通信异常信息为{ex.Message}"); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="bytData"></param> /// <returns></returns> public bool Send(byte[] bytData) { bool flag = false; try { if (tSocket != null) { lock (qLock) { if (tSocket.Connected) { int n = tSocket.Send(bytData); flag = true; } else { NotifyCommandEvent?.Invoke("Break", "SendData fail"); flag = false; } } } return(flag); } catch (Exception ex) { NotifyCommandEvent?.Invoke("Break", ex.Message); return(false); } }
/// <summary> /// 接收消息 /// </summary> /// <param name="state"></param> private void Recv(object state) { Socket client = state as Socket; byte[] bytebuffer = new byte[byteLen]; lock (qLock) { while (true) { try { if (tSocket != null) { if (tSocket.Connected) { for (int i = 0; i < 50; i++) { bytebuffer[i] = 0; } int nLen = tSocket.Receive(bytebuffer); if (nLen > 0) { NotifyCommandEvent?.Invoke("RecvData", bytebuffer); } else { NotifyCommandEvent?.Invoke("Break", "接受报文长度为0"); } } } else { NotifyCommandEvent?.Invoke("Break", "与PLC断开连接"); } } catch (Exception ex) { NotifyCommandEvent?.Invoke("Break", $"连接断开{ex.Message}"); } } } }