private void Send(TcpClientSocket _tcpSocket, string _sendMessage) { if (_tcpSocket != null && _tcpSocket.Connected) { if (_sendMessage.ToLower() != "disconnect") { byte[] msgPayload = Encoding.ASCII.GetBytes(_sendMessage); _tcpSocket.SendAsync(msgPayload); } else { _tcpSocket.Disconnect(); return; } } else { return; } }
/// <summary> /// Sends a message to the server. /// </summary> private void BtnSend_Click(object sender, EventArgs e) { // If the message is valid. if (TbMsg.Text != string.Empty && TbMsg.Text != null) { string msg = TbMsg.Text; // If connected to the server. if (socket != null && socket.Connected) { // If the message is not a command. if (!RunCommand(msg)) { // Convert the message into a byte array. byte[] msgPayload = Encoding.ASCII.GetBytes(msg); // Send the message asynchronously. socket.SendAsync(msgPayload); // Clears the message entry textbox. TbMsg.Text = string.Empty; // Display the message was sent. AppendText($"\nYou: {msg}"); } } else { MessageBox.Show("You are not connected to the server."); TbMsg.Clear(); } } else { //MessageBox.Show("Please enter a message before sending", "No Message To Send"); } }
/// <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"); } }