private void ChatBT_Send_Click(object sender, EventArgs e) { string msg = ClintRTB_snd.Text; if (msg == "") { MessageBox.Show("消息不能为空!"); return; } ClintRTB_snd.Text = ""; ClientRTB_msg.AppendText("你 : " + msg + "\r\n"); sendMessage(msg); }
private void ReadComplete(IAsyncResult ar) { int bytesRead; try { lock (streamToServer) { bytesRead = streamToServer.EndRead(ar); } if (bytesRead == 0) { throw new Exception("读取到0字节"); } string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); if (msg.Substring(0, 3) == "$$$") { readLists(msg); } else { ClientRTB_msg.AppendText(msg); } Array.Clear(buffer, 0, buffer.Length); // 清空缓存,避免脏读 lock (streamToServer) { AsyncCallback callBack = new AsyncCallback(ReadComplete); streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null); } } catch (Exception ex) { if (streamToServer != null) { streamToServer.Dispose(); } Client.Close(); Console.WriteLine(ex.Message); } }