C# 使用UdpClient发送组播消息
实现的功能:
1、服务端发送消息至预定义的组播地址 2、加入到组播组的客户端均能收到服务端发送的消息
using System.Net;
using System.Net.Sockets;
using System.Threading;
服务端源码:
private static IPAddress GroupAddress =
IPAddress.Parse("224.100.0.1"); //定义组播地址
private static int GroupPort
=11000;
//定义发送组播时客户端的监听端口
private
static void Send(String message)
{
UdpClient myUdpClient = new UdpClient(); //建立发送端的UdpClient实例
IPEndPoint groupEP = new
IPEndPoint(GroupAddress,GroupPort);//定义或设置IP地址与端口
try
{
byte[] bytes = Encoding.UTF8.GetBytes(message);//将字符串转换成字节数组
myUdpClient.Send(bytes, bytes.Length,
groupEP);//使用UdpClient发送字节数据
myUdpClient.Close();//关闭UDP连接
MessageBox.Show("消息发送成功!");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
private void btnSend_Click(object sender, EventArgs e)
{
string message = txttxnr.Text.Trim();
Send(message);//调用Send方法发送消息
}
客户端源码:
private void MainForm_Load(object sender,
EventArgs e)
{
Thread myThread = new
Thread(ReceiveData);//使用线程启动ReceiveData()
myThread.IsBackground = true;//是否为后台线程
myThread.Start();//启动线程
}
private const int Groupport =11000;
//声明组播端口
private static readonly IPAddress GroupAddress =
IPAddress.Parse("224.100.0.1");//定义组播地址
private void ReceiveData() //循环接收UDP包,并将数据添加到listbox中
{
bool loop=true;
UdpClient receiveUdpClient = new
UdpClient(Groupport);//建立接收端的UdpClient实例,并定义端口
IPEndPoint GroupEP = new IPEndPoint(GroupAddress,Groupport);
//获取或设置IP地址与端口
try
{
receiveUdpClient.JoinMulticastGroup(GroupAddress);//加入组播组
receiveUdpClient.EnableBroadcast =
true;//设置是否发送或接收广播数据包
while (loop) //接收并显示消息内容
{
byte[]
receiveBytes = receiveUdpClient.Receive(ref GroupEP);
string
receiveMessage = Encoding.UTF8.GetString(receiveBytes, 0,
receiveBytes.Length);
AddItem(lst_Receive,
receiveMessage);//调用方法将消息内容发送到listbox中
MessageBox.Show(receiveMessage);
}
//receiveUdpClient.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
delegate void AddItemDelegate(ListBox
listbox, string text);
private void AddItem(ListBox listbox, string text)
{
if (listbox.InvokeRequired)//在线程中调用创建于其他线程中的空间需要使用Invoke方法
{
AddItemDelegate d = AddItem;
listbox.Invoke(d, new object[] { listbox, text });
}
else
{
listbox.Items.Add(text);
listbox.SelectedIndex = listbox.Items.Count - 1;
listbox.ClearSelected();
}
}
浙公网安备 33010602011771号