private void RichTextBox2_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) { if (bConnected) { try { lock (this) { RichTextBox1.Text = "客户机:" + RichTextBox2.Text + RichTextBox1.Text; tWriter.WriteLine(RichTextBox2.Text); tWriter.Flush(); RichTextBox2.Text = ""; RichTextBox2.Focus(); } } catch (Exception) { MessageBox.Show("与服务器连接断开!"); } } else { MessageBox.Show("未与服务器建立连接,无法与服务器通信!"); } } }
private void RichTextBox2_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13)//按下的是回车 { if (bConnected) { try { //RichTextBox2_KeyPress()和AcceptMessage()都将向 //RichTextBox1写入字符,可能冲突,需要多线程互斥 lock (this) { RichTextBox1.Text = "服务器:" + RichTextBox2.Text + RichTextBox2.Text + RichTextBox1.Text; //客户机聊天信息写入网络流便于服务器接收 tWriter.WriteLine(RichTextBox2.Text); tWriter.Flush(); //清理当前缓冲区,使缓冲数据写入基础设备 RichTextBox2.Text = ""; //发送成功后,清空输入框并聚焦 RichTextBox2.Focus(); } } catch (Exception) { MessageBox.Show("无法与客户机通信!"); } } else { MessageBox.Show("未与客户机建立连接,无法与客户机通信!"); } } }