// 接收数据 public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.thisSocket.EndReceive(asyn); string msg = ""; string name = ""; //theSockId.dataBuffer byte[] headLength = theSockId.dataBuffer.Skip(0).Take(2).ToArray(); byte[] dd = theSockId.dataBuffer.Skip(2).Take(2).ToArray(); Int16 cmd = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(theSockId.dataBuffer.Skip(2).Take(2).ToArray(), 0)); switch (cmd) { case 10000: // 登录成功 { _login = true; } break; case 11001: // 收到广播消息 { byte[] accountId = theSockId.dataBuffer.Skip(4).Take(4).ToArray(); Int16 accountNameSize = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(theSockId.dataBuffer.Skip(8).Take(2).ToArray(), 0)); byte[] AccountName = theSockId.dataBuffer.Skip(10).Take(accountNameSize).ToArray(); name = Encoding.ASCII.GetString(AccountName); Int16 contentSize = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(theSockId.dataBuffer.Skip(10 + accountNameSize).Take(2).ToArray(), 0)); byte[] contentByte = theSockId.dataBuffer.Skip(10 + accountNameSize + 2).Take(contentSize).ToArray(); msg = Encoding.ASCII.GetString(contentByte); AppendToRichEditControl(name + ":" + msg + "\r\n"); } break; } // 等待数据 WaitForData(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket已经关闭!\n"); } catch (SocketException se) { if (se.ErrorCode == 10054) { string msg = "服务器" + "停止服务!" + "\n"; MessageBox.Show(msg, "提示"); _socket.Close(); _socket = null; button2.Enabled = true; } else { button2.Enabled = true; MessageBox.Show(se.Message, "提示"); } } }
// 等待数据 public void WaitForData() { try { if (pfnCallBack == null) { // 当连接上的客户有写的操作的时候,调用回调函数 pfnCallBack = new AsyncCallback(OnDataReceived); } SocketPacket socketPacket = new SocketPacket(); socketPacket.thisSocket = _socket; result = _socket.BeginReceive(socketPacket.dataBuffer, 0, socketPacket.dataBuffer.Length, SocketFlags.None, pfnCallBack, socketPacket); } catch (SocketException se) { MessageBox.Show(se.Message, "提示"); } }