C#使用udp如何实现消息的接收和发送
作者:王者无双 时间:2022-05-26 20:56:01
使用udp实现消息的接收和发送
代码比较简单,但是别忘记关闭防火墙进行测试。
首先便是服务端,使用Socket进行实现,参考代码如下:
private static Socket udpServer;
static void startUdpReceive()
{
Console.WriteLine("------startUdpReceive--");
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));
new Thread(ReceiveMessage)
{
IsBackground = true
}.Start();
}
private static void ReceiveMessage()
{
Console.WriteLine("------ReceiveMessage--");
while (true)
{
byte[] data = new byte[1024];
EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
int count = udpServer.ReceiveFrom(data, ref endPoint);
if (count > 0)
{
string message = Encoding.UTF8.GetString(data, 0, count);
Console.WriteLine
("-----从ip" + (endPoint as IPEndPoint).Address.ToString()
+ ":" + (endPoint as IPEndPoint).Port + "Get" + message);
}
}
}
在绑定socket端口的时候,需要提供绑定的ip和端口号,如这里是
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));
本机ip是是192.168.2.106,绑定端口是10023。然后使用while循环监听消息。对于本机来说,也可以使用 udpServer.Bind(new IPEndPoint(IPAddress.Any, 10023)); 只绑定端口,对于ip则不限制。
也可以不用Socket而是直接使用UdpClient类来写接收端,效果类似:
static UdpClient udpcRecv;
public static void UdpServices()
{
try
{
IPAddress ip = IPAddress.Parse("192.168.2.106");
IPEndPoint remoteIpep = new IPEndPoint(ip, 10023);
udpcRecv = new UdpClient(remoteIpep);
Thread thrRecv = new Thread(ReceiveMessage22);
thrRecv.IsBackground = true;
thrRecv.Start();
}
catch (Exception ex)
{
MessageBox.Show("错误", "请检查网络");
}
}
private static void ReceiveMessage22()
{
IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("-----remoteIpep:" + remoteIpep.Address + ":" + remoteIpep.Port);
while (true)
{
try
{
byte[] bytRecv = udpcRecv.Receive(ref remoteIpep);
string message = Encoding.UTF8.GetString(
bytRecv, 0, bytRecv.Length);
Console.WriteLine("-----reveice message:" + message);
}
catch (Exception ex)
{
MessageBox.Show("UDP异常", ex.Message);
}
}
}
接下来是发送端:
UdpClient udpClient = new UdpClient();
try
{
udpClient.Connect("192.168.2.106", 10023);
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there??????");
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
如果代码爆红则应该是导包的问题,加入以下即可。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using System.Management;
using System.Threading;
上面都写好后可以测试了,但是我却遇到了问题,后面才知道是电脑端防火墙没开导致,所以和电脑端调试网络通信的时候,需要关闭防火墙,才能收到数据。
C# 运用UDP
面试的时候偶尔会问到UDP和TCP的一个区别。
TCP是一种面向连接的、可靠的、基于字节流的传输层通信协议。举例:打电话,需要双方都接通,才能进行对话。特点:效率低,数据传输比较安全。
UDP是一种面向无连接的传输层通信协议。举例:发短信,不需要双方建立连接,但是,数据报的大小应限制在64k以内。特点:效率高,数据传输不安全,容易丢包
然后发现在网上查找关于C#运行UDP的实例,确实不好找,杂乱无章。痛定思痛!
进行一个简单的发送和接收测试。
目前,UDP本人亲自用过的场景,客户端和服务端需要进行数据传输,但是服务端,在开始时是连接的别的网络,切换过来之后,并不能知道当前的一个具体的IP地址。但是客户端的IP地址是固定的,此种场景下,服务端网络切换过来之后,建立UDP服务端,像指定的客户端(IP地址和端口号)发送数据,即可知道当前服务端的ip地址。
服务端界面
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.Tasks;
using System.Windows.Forms;
namespace MyTest.UDP
{
public partial class UDP_Sever : Form
{
IPEndPoint remotePoint;
UdpClient sever = null;
public UDP_Sever()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPAddress remoteIP = IPAddress.Parse(textBox1.Text.Trim()); //假设发送给这个IP
int remotePort =int.Parse(textBox2.Text.Trim());
remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
sever = new UdpClient();
}
private void button2_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(textBox3.Text.Trim()))
{
string sendString = textBox3.Text.Trim();//要发送的字符串
byte[] sendData = Encoding.Default.GetBytes(sendString);//要发送的字节数组
sever.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
textBox3.Text = "";
}
}
private void UDP_Sever_FormClosing(object sender, FormClosingEventArgs e)
{
sever.Close();
}
}
}
客户端界面
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 MyTest.UDP
{
public partial class UDP_Client : Form
{
UdpClient client = null;
IPEndPoint remotePoint;
string receiveString = null;
byte[] receiveData = null;
public UDP_Client()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
//实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
remotePoint = new IPEndPoint(IPAddress.Any, 0);
client = new UdpClient(int.Parse(textBox2.Text.Trim()));
Thread thread = new Thread(Revice);
thread.IsBackground = true;
thread.Start();
}
private void Revice()
{
while (true)
{
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
listBox1.Items.Add(remotePoint.Address.ToString()+":"+ receiveString);
}
}
}
}
亲测有效!
来源:https://blog.csdn.net/bawang_cn/article/details/120139559