📄 udpserver.cs
字号:
using System;
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;
namespace UdpServer
{
public partial class UdpServer : Form
{
//创建一个Thread类
private Thread thread1;
//创建一个UdpClient对象,来接收消息
private UdpClient udpReceive;
private UdpClient udpSend;
public UdpServer()
{
InitializeComponent();
}
private void BtnSend_Click(object sender, EventArgs e)
{
//初始化UdpClient
udpSend = new UdpClient();
//允许发送和接收广播数据报
udpSend.EnableBroadcast = true;
//必须使用组播地址范围内的地址
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.10"), 8001);
//将发送内容转换为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(TbxMessage.Text);
//设置重传次数
int retry = 0;
while (true)
{
try
{
//发送组播信息
udpSend.Send(bytes, bytes.Length, iep);
break;
}
catch
{
if (retry < 3)
{
retry++; continue;
}
else
{
DialogResult result = MessageBox.Show("发送失败!");
break;
}
}
}
//清空TbxMesage中的内容
TbxMessage.Clear();
//光标还原
TbxMessage.Focus();
}
private void ReceiveMessage()
{
//在本机指定的端口接收
IPEndPoint remoteIpEndIPoint = new IPEndPoint(IPAddress.Any, 8002);
udpReceive = new UdpClient(remoteIpEndIPoint);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
//接收从远程主机发送过来的信息
while (true)
{
//ref表示引用类型的 IPPoint实例接收消息
byte[] receiveBytes = udpReceive.Receive(ref iep);
string returnData = Encoding.UTF8.GetString(receiveBytes);
string message = "来自" + iep.ToString() + "的消息";
//显示消息 并以message为消息的标题
DialogResult result = MessageBox.Show(returnData, message);
}
}
private void UdpServer_Load(object sender, EventArgs e)
{
//初始化该线程并指定线程执行时要调用的方法
thread1 = new Thread(new ThreadStart(ReceiveMessage));
//启动线程
thread1.Start();
}
private void UdpServer_FormClosing(object sender, FormClosingEventArgs e)
{
//关闭UdpClient连接
udpReceive.Close();
udpSend.Close();
//终止线程
thread1.Abort();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -