private void MessageCallBack(IAsyncResult aResult) { try { byte[] receivedData = new byte[1500]; receivedData = (byte[])aResult.AsyncState; ASCIIEncoding aEncoding = new ASCIIEncoding(); string receivedMessage = aEncoding.GetString(receivedData); //richTextBox.AppendText(Environment.NewLine + msg); //richTextBox.SelectionAlignment = HorizontalAlignment.Right; if (Rchtxt_Chat.Text == "") { Rchtxt_Chat.SelectionColor = Color.Green; Rchtxt_Chat.AppendText(Environment.NewLine + frm_Home.Username + " : " + receivedMessage.Trim()); Rchtxt_Chat.SelectionAlignment = HorizontalAlignment.Left; } else { Rchtxt_Chat.SelectionColor = Color.Green; Rchtxt_Chat.AppendText(Environment.NewLine + frm_Home.Username + " : " + receivedMessage.Trim()); Rchtxt_Chat.SelectionAlignment = HorizontalAlignment.Left; } Buffer = new byte[1500]; socket.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref Remote, new AsyncCallback(MessageCallBack), Buffer); } catch (InvalidOperationException) { MessageBox.Show("Check your connection", "Be Connect+ - Users are not connected", MessageBoxButtons.OK, MessageBoxIcon.Stop); } }
private void btn_Send_Click(object sender, EventArgs e) { if (tn_Connect.Text == "Disconnect") { if (txt_Placeholder.Text != "") { ASCIIEncoding aEncoding = new ASCIIEncoding(); byte[] Sendmsg = new byte[1500]; Sendmsg = aEncoding.GetBytes(txt_Placeholder.Text); socket.Send(Sendmsg); if (Rchtxt_Chat.Text == "") { Rchtxt_Chat.SelectionColor = Color.Red; Rchtxt_Chat.AppendText(Environment.NewLine + Dns.GetHostName() + " : " + txt_Placeholder.Text.Trim()); Rchtxt_Chat.SelectionAlignment = HorizontalAlignment.Right; } else { Rchtxt_Chat.SelectionColor = Color.Red; Rchtxt_Chat.AppendText(Environment.NewLine + Dns.GetHostName() + " : " + txt_Placeholder.Text.Trim()); Rchtxt_Chat.SelectionAlignment = HorizontalAlignment.Right; } } else { MessageBox.Show("Enter any Message to send", "Be Connect+ - No Message typed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } txt_Placeholder.Lines = null; txt_Placeholder.Clear(); txt_Placeholder.Focus(); Rchtxt_Chat.SelectionStart = Rchtxt_Chat.Text.Length; Rchtxt_Chat.ScrollToCaret(); } else { MessageBox.Show("Please click Connect button", "Be Connect+ - Users not connected", MessageBoxButtons.OK, MessageBoxIcon.Stop); } }