private static void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. ClientStateObject state = (ClientStateObject)ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); Console.WriteLine("Bytes Read: " + bytesRead); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); response = state.sb.ToString(); } if (response.Equals("User created!") || response.Equals("User already exists!") || response.Equals("Login successful!") || response.Equals("Admin Login successful!") || response.Equals("Password incorrect!") || response.Equals("User doesn't exist!") || response.Equals("Some Messages") || response.Equals("Message Sent!") || isValidJSON(response) == true) { // All the data has arrived; put it in response. if (isValidJSON(response) == true) { List <ChatMessage> receivedChatMessageList = JsonConvert.DeserializeObject <List <ChatMessage> >(response); currentChatForm.populateChat(receivedChatMessageList); } // Signal that all bytes have been received. state.sb.Clear(); receiveDone.Set(); Receive(client); } else { // Get the rest of the data. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } } catch (Exception e) { Console.WriteLine(e.ToString() + "Exception"); } }
/** * Receive and ReceiveCallBack are used to receive, decode, and handle the data * received from the server as a response to the request from the client; * @param client - the current socket, used to send requests */ private static void Receive(Socket client) { try { // Create the state object. ClientStateObject state = new ClientStateObject(); state.workSocket = client; // Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch (Exception e) { Console.WriteLine(e.ToString()); } }