//发送大量文本消息
private void sendMessage()
{
if (richTextBox_send.Text.Trim().Length==0 && richTextBox_send.Rtf.IndexOf("pict")<0)
{
MessageBox.Show("发送的消息不能为空");
return;
}
if (Encoding.Default.GetByteCount(richTextBox_send.Text) > 1024*3)
{
MessageBox.Show("发送的内容过长");
return;
}
try
{
//初始化接受套接字:寻址方案,以字符流方式和Tcp通信
socketSent = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
//设置目标服务器IP地址和端口
ipSent = new IPEndPoint(IPAddress.Parse(ip), 8001);
//与目标服务器进行连接
socketSent.Connect(ipSent);
//将要发送的消息转化为字节流,然后发送
socketSent.Send(Encoding.Default.GetBytes("MSG"));
Thread.Sleep(100);
//循环发送
//设置缓冲区为1024byte
byte[] buff = new byte[1024];
int len = 0;
MemoryStream data = new MemoryStream();
richTextBox_accept.Rtf = richTextBox_accept.Rtf.Replace(@"\f1\par", "");
richTextBox_send.SaveFile(data, RichTextBoxStreamType.RichText);
data.Position = 0;
while ((len = data.Read(buff, 0, 1024)) != 0)
{
//按实际的字节总量发送信息
socketSent.Send(buff, 0, len, SocketFlags.None);
//richTextBox_accept.AppendText(Encoding.Default.GetString(buff));
}
data.Close();
data.Dispose();
socketSent.Send(Encoding.Default.GetBytes("END"));
socketSent.Close();
}
catch
{
MessageBox.Show(user + "已经下线!");
return;
}
if (richTextBox_accept.Text != "")
{
richTextBox_accept.SelectionColor = Color.Green;
richTextBox_accept.AppendText("\n" + currentUser + " " + DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss") + "\n");
richTextBox_accept.SelectionColor = Color.Black;
richTextBox_accept.Select(richTextBox_accept.Text.Length, 0);
richTextBox_accept.SelectedRtf = richTextBox_send.Rtf;
richTextBox_accept.Update();
richTextBox_accept.Select(richTextBox_accept.Rtf.Length, 0);
}
else
{
richTextBox_accept.SelectionColor = Color.Green;
richTextBox_accept.AppendText(currentUser + " " + DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss") + "\n");
richTextBox_accept.SelectionColor = Color.Black;
richTextBox_accept.Select(richTextBox_accept.Text.Length, 0);
richTextBox_accept.SelectedRtf = richTextBox_send.Rtf;
richTextBox_accept.Update();
richTextBox_accept.Select(richTextBox_accept.Rtf.Length, 0);
}
this.richTextBox_send.Clear();
richTextBox_accept.ScrollToCaret();
}
private void btn_close_Click(object sender, EventArgs e)
{
this.Close();
}
//组合键发送消息
private void richTextBox_send_KeyUp(object sender, KeyEventArgs e)
{
if ((Control.ModifierKeys & Keys.Control) != 0 && e.KeyCode == Keys.Enter)
{
if (radioBtn_sendStyle2.Checked)//发送模式选择为Enter+Ctrl
{ sendMessage(); }
}
else if (e.KeyCode == Keys.Enter)
{
if (radioBtn_sendStyle1.Checked)//发送模式选择为Enter
{
sendMessage();
}
}
}
C# 局域网聊天 发送信息
本文转载:CSDN博客