/// <summary> /// 向指定客户端发送数据(基础) /// </summary> /// <param name="iClient">客户端</param> /// <param name="data">字节数组数据</param> public void SendData(IClient iClient, byte[] data) { try { if (iClient != null) { //异步发送数据 //cModel.ClientSocket.Send(data); iClient.WorkSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), iClient); iClient.BufferInfo.SendBuffer = data; TcpServerGetLog(iClient, LogType.SendData, DataToolManager.HexByteArrayToString(data)); } } catch (SocketException ex) { if (iClient == null) { ClientSocketList.Remove(iClient); TcpServerReturnClientCount(ClientSocketList.Count); return; } ShutdownClient(iClient); TcpServerOfflineClient(iClient); TcpServerErrorMsg(string.Format("向客户端发送数据时发生错误,错误原因:{0}", ex.Message)); TcpServerGetLog(iClient, LogType.SendData, ex.Message); ClientSocketList.Remove(iClient); TcpServerReturnClientCount(ClientSocketList.Count); } }
/// <summary> /// 异步接收数据 /// </summary> /// <param name="ar"></param> private void ClientReadCallback(IAsyncResult ar) { IClient iClient = (IClient)ar.AsyncState; try { int bytesRead = iClient.WorkSocket.EndReceive(ar); if (bytesRead > 0) { //byte[] haveDate = ReceiveDateOne.DateOneManage(iClient, bytesRead);//接收完成之后对数组进行重置 byte[] bytes = new byte[bytesRead]; Array.Copy(iClient.BufferInfo.ReceivedBuffer, 0, bytes, 0, bytesRead); string clientRecevieStr = ""; #region WebSocket验证 //验证websocket握手协议 if (iClient != null && iClient.ClientStyle != ClientStyle.WebSocket) { clientRecevieStr = ASCIIEncoding.Default.GetString(iClient.BufferInfo.ReceivedBuffer, 0, bytesRead); //如果客户端不存在则退出检测 WebSocketHandShake(iClient, clientRecevieStr, bytes); } if (iClient.ClientStyle == ClientStyle.WebSocket) { string webstr = AnalyticData(bytes, bytes.Length); clientRecevieStr = webstr; bytes = Encoding.Default.GetBytes(clientRecevieStr); } #endregion TcpServerRecevice(iClient, bytes); TcpServerGetLog(iClient, LogType.ReceviedData, DataToolManager.HexByteArrayToString(bytes)); iClient.WorkSocket.BeginReceive(iClient.BufferInfo.ReceivedBuffer, 0, iClient.BufferInfo.ReceivedBuffer.Length, 0, new AsyncCallback(ClientReadCallback), iClient); } else if (bytesRead == 0) { //接收数据长度为0时,标示客户单下线 if (iClient != null) { ShutdownClient(iClient); TcpServerStateInfo(iClient, string.Format("<{0}:{1}>---下线", iClient.Ip, iClient.Port), SocketState.ClientOnOff); RemoveClient(iClient, "客户端下线"); TcpServerOfflineClient(iClient); ClientSocketList.Remove(iClient); TcpServerReturnClientCount(ClientSocketList.Count); } } } catch (Exception ex) { TcpServerErrorMsg(string.Format("接收客户端数据时发生错误,错误原因:{0}", ex.Message)); int i = ex.Message.IndexOf("远程主机强迫关闭了一个现有的连接"); if (iClient != null && i != -1) { RemoveClient(iClient, ex.Message); } iClient = null; } }