using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
{
public partial class Form1 : Form
{
delegate void AppendStringCallback(string text);
AppendStringCallback appendStringCallback;
//使用的接收端口号
private int port = 8001;
private UdpClient udpClient;
{
InitializeComponent();
appendStringCallback = new AppendStringCallback(AppendString);
}
{
if (richTextBox1.InvokeRequired)
{
richTextBox1.Invoke(appendStringCallback, text);
}
else
{
richTextBox1.AppendText(text + "\r\n");
}
}
{
udpClient = new UdpClient(port);
//必须使用组播的地址范围内的地址
udpClient.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);
IPEndPoint remote = null;
//接收从远程主机发送过来的信息
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
AppendString(string.Format("来自{0}:{1}", remote, str));
}
catch
{
//退出循环,结束线程
break;
}
}
}
{
UdpClient myUdpClient = new UdpClient();
try
{
//允许发送和接收广播数据报
myUdpClient.EnableBroadcast = true;
//必须使用组播地址范围内的地址
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), port);
//将发送内容转换为字节数组
byte[] bytes = Encoding.UTF8.GetBytes(txbSend.Text);
//向子网发送信息
myUdpClient.Send(bytes, bytes.Length, iep);
txbSend.Clear();
txbSend.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
//将线程设为后台运行
receiveThread.IsBackground = true;
receiveThread.Start();
}
{
udpClient.Close();
}
}
}