/** * This method handles receiving name data from the client and printing that name, only called once upon a client connecting. */ private void RecieveNameCallback(IAsyncResult ar) { var current = (Socket)ar.AsyncState; var received = 0; try { received = current.EndReceive(ar); if (received == 0) { return; } // Creating a new client from the data received from the client, the client class has an overloaded constructor that takes a byte array and converts that data. client = new Client(mReceivedData); mClients.Add(client); var line = ""; line = client.Name + " has entered the room"; AppFunctions.AppendTextBox(line, receivedTxt); foreach (Socket client in mClientSockets) { AppFunctions.SendText(line, client, mSendData); } // Ensure received data array is cleared for the next piece of data. Array.Clear(mReceivedData, 0, mReceivedData.Length); } catch (SocketException) { } }
/** * Method for handling all text sent from a client. * */ private void RecieveCallback(IAsyncResult ar) { var current = (Socket)ar.AsyncState; var received = 0; var currentIndex = 0; currentIndex = UpdateIndex(current); try { received = current.EndReceive(ar); if (received == 0) { return; } // Parsing the data sent, need to trim the end of any null characters. var text = ""; text = Encoding.ASCII.GetString(mReceivedData, mReceivedData[received], mReceivedData.Length).TrimEnd('\0'); // Handles closing the socket when the client clicks the exit button. if (text == "/exit") { var line = ""; line = mClients[currentIndex].Name + " has left the room"; AppFunctions.AppendTextBox(line, receivedTxt); foreach (Socket client in mClientSockets) { AppFunctions.SendText(line, client, mSendData); } // Remove client from the client list and the curent socket from the socket list, clear the received data array so that other people can still send data. mClientSockets.Remove(current); mClients.Remove(mClients[currentIndex]); Array.Clear(mReceivedData, 0, mReceivedData.Length); } else { var line = ""; line = mClients[currentIndex].Name + " says: " + text; AppFunctions.AppendTextBox(line, receivedTxt); // Send the received data to all clients. foreach (Socket client in mClientSockets) { AppFunctions.SendText(line, client, mSendData); } // Clear the data array for the next piece of incoming data. Array.Clear(mReceivedData, 0, mReceivedData.Length); current.BeginReceive(mReceivedData, 0, mReceivedData.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), current); } } catch (SocketException) { } }