private void ReceiveCallback(IAsyncResult result) { UserConnectionInfo connection = (UserConnectionInfo)result.AsyncState; Socket client = connection.Socket; Packets newReadPacket = new Packets(); try { int bytesRead = connection.Socket.EndReceive(result); MemoryStream memstr = new MemoryStream(connection.Buffer, 0, bytesRead); if (bytesRead > 5)//получаем длину хедера { Packets dataViewer = newReadPacket.HandleMessagePacket(bytesRead, memstr); if (dataViewer != null) { txtmgr.ShowMessage(ServerBox, dataViewer.GetNickname, dataViewer.GetMessage); } else connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); } else connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); } catch (SocketException exc) { CloseConnection(connection); txtmgr.ShowSystemMessage(ServerBox, "Socket exception: " + exc.SocketErrorCode); } catch (Exception exc) { CloseConnection(connection); txtmgr.ShowSystemMessage(ServerBox, "Exception: " + exc); } }
private void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); MemoryStream memstr = new MemoryStream(state.buffer, 0, bytesRead); Packets newReadPacket = new Packets(); if (bytesRead > 5)//получаем длину хедера { Packets dataViewer = newReadPacket.HandleMessagePacket(bytesRead, memstr); if (dataViewer != null) { txtmgr.ShowMessage(ClientBox, dataViewer.GetNickname, dataViewer.GetMessage); } else client.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); client.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); } else client.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); } catch (Exception e) { txtmgr.ShowSystemMessage(ClientBox, e.ToString()); } }