1、UI界面和最终实现功能测试
2、代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UdpTest
{
public partial class MaiForm : Form
{
public MaiForm()
{
InitializeComponent();
}
bool isContinueSend = false; //是否连续发送
// 创建UdpClient实例
Socket udpClient;
Thread t;
Thread t2;
string udpRecv;
private void MaiForm_Load(object sender, EventArgs e)
{
udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpClient.Bind(new IPEndPoint(IPAddress.Parse(txtLocalIp.Text), int.Parse(txtLocalPort.Text)));
t = new Thread(sendMsg);
t.Start();
t2 = new Thread(ReciveMsg);
t2.Start();
timer1.Start();
}
/// <summary>
/// 向特定ip的主机的端口发送数据报
/// </summary>
void sendMsg()
{
EndPoint point = new IPEndPoint(IPAddress.Parse(txtSendIp.Text), int.Parse(txtSendPort.Text));
while (true)
{
if(isContinueSend)
{
string msg = txtSend.Text;
udpClient.SendTo(Encoding.Default.GetBytes(msg), point);
Thread.Sleep(1000);
}
}
}
/// <summary>
/// 接收发送给本机ip对应端口号的数据报
/// </summary>
void ReciveMsg()
{
while (true)
{
EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
byte[] buffer = new byte[1024];
int length = udpClient.ReceiveFrom(buffer, ref point);//接收数据报
string strRecvTemp = Encoding.UTF8.GetString(buffer, 0, length);
if (length > 0)
{
udpRecv += point.ToString() + ": " + strRecvTemp + "\r\n";
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
EndPoint point = new IPEndPoint(IPAddress.Parse(txtSendIp.Text), int.Parse(txtSendPort.Text));
string msg = txtSend.Text;
udpClient.SendTo(Encoding.UTF8.GetBytes(msg), point);
}
private void timer1_Tick(object sender, EventArgs e)
{
txtUdpRecv.Text = udpRecv;
}
private void MaiForm_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(0); //强制关闭所有线程
Application.Exit();
}
private void checkContinueSend_CheckedChanged(object sender, EventArgs e)
{
isContinueSend = checkContinueSend.Checked;
if(isContinueSend)
{
btnSend.Enabled = false;
}
else
{
btnSend.Enabled = true;
}
}
}
}
3、下载连接
https://download.csdn.net/download/panjinliang066333/89616042