/// <summary> /// Connects to the server and sends the username. /// </summary> /// <param name="userName"> The client's username for the chat. </param> void ConnectToServer(string userName) { if (!string.IsNullOrWhiteSpace(userName)) { socket = new TcpClientSocket(); socket.AsyncConnectionResult += (s, e) => { // If connected to the server if (e.Connected) { // Send the username to the server. byte[] msgPayload = Encoding.ASCII.GetBytes("<c>username" + userName); socket.SendAsync(msgPayload); // Start receiving messages from the server. beginReceiving(socket); rtbClientMessages.InvokeIfRequired(s1 => { // Displays that a client has connected if (s1.Text.Length <= 0) { this.Invoke((MethodInvoker)(() => rtbClientMessages.AppendText("Connected to the server."))); } else { this.Invoke((MethodInvoker)(() => rtbClientMessages.AppendText("\nConnected to the server."))); } }); btnConnect.InvokeIfRequired(bc => { bc.Text = "Connected"; }); btnSend.InvokeIfRequired(bs => { bs.Enabled = true; }); } else { ConnectToServer(userName); } }; try { // Set the connection controls to disabled btnConnect.Text = "Connecting"; btnConnect.Enabled = false; tbUsername.Enabled = false; // Connect to the server. socket.ConnectAsync(ipEnd); } catch (Exception ex) { // Set the conncet controls to enabled btnConnect.Text = "Connect"; btnConnect.Enabled = true; tbUsername.Enabled = true; MessageBox.Show(ex.ToString(), "Cannot Connect To Server"); } } else { MessageBox.Show("Please enter a valid username.", "Invalid Username"); } }