UDP聊天代码发送消息客户端代码
添加引用
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
//发送消息按钮事件
private void button1_Click(object sender, System.EventArgs e)
{
this.button1.Enabled=false;
try
{
// IPHostEntry rHost=Dns.GetHostByName(textBox3.Text);
UdpClient uc=new UdpClient(textBox1.Text,int.Parse(textBox2.Text));
byte[] sendbuf=Encoding.UTF8.GetBytes(richTextBox1.Text);
uc.Send(sendbuf, sendbuf.Length);
this.statusBar1.Text="UDP信息发送完成";
int ListCount=0;
if(listView1.Items.Count==0)
{
listView1.Items.Add(DateTime.Now.ToString());
listView1.Items[0].SubItems.Add(textBox1.Text);
listView1.Items[0].SubItems.Add(richTextBox1.Text);
}
else
{
ListCount=listView1.Items.Count;
listView1.Items.Add(DateTime.Now.ToString());
listView1.Items[ListCount].SubItems.Add(textBox1.Text);
listView1.Items[ListCount].SubItems.Add(richTextBox1.Text);
}
uc.Close();
}
catch(Exception y)
{
MessageBox.Show(this,y.Message,"发送失败",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
this.button1.Enabled=true;
}