UDP通信特点:
无连接,多对多
不可靠
面向数据报
效率高
UDP中的分包与黏包
分包:一段数据被分为两段或多段传输,在UDP通信方式中,因为UDP的不可靠性无法保证有序传输,因此尽量避免UDP自动分包。
其中一种方式是保证消息包大小在548字节(互联网)或1472字节(局域网)以下;
若数据量过大,可采用手动分包,但我们必须将UDP变为可靠的(如为每段数据添加序号),才能保证正常处理手动分包后的消息。
黏包:在UDP通信方式中,UDP不会对数据进行合并发送,因此不会出现黏包。
代码实现概述:
不同于TCP通信方式,UDP中服务端与客户端代码实现流程相似,如下:
1.创建socket套接字对象
2.利用Bind方法将本机地址与套接字绑定
3.利用ReceiveFrom与SendTo方法进行通信
4.用Shutdown方法释放连接
5.关闭套接字
本文中服务端与客户端通信,仅以相互发送字符串为例。通过创建对应的类对象并利用序列化与反序列化,也可以实现复杂数据的传输。文章来源:https://www.toymoban.com/news/detail-764440.html
服务端代码:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UdpServerStudy
{
class Program
{
public static ServerSocket serverSocket;
static void Main(string[] args)
{
//声明套接字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//Bind绑定
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);
socket.Bind(ipPoint);
Console.WriteLine("服务器开启");
//收消息
byte[] bytes = new byte[512];
EndPoint receivePoint = new IPEndPoint(IPAddress.Any, 0);
int len = socket.ReceiveFrom(bytes, ref receivePoint);
Console.WriteLine((receivePoint as IPEndPoint).Address.ToString() + "发来了:" + Encoding.UTF8.GetString(bytes, 0, len));
//发消息
socket.SendTo(Encoding.UTF8.GetBytes("欢迎发送消息给服务器"), receivePoint);
//关闭
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Console.ReadKey();
}
}
}
客户端代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class ClientUDP : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//声明套接字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//Bind绑定
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
socket.Bind(ipPoint);
//发消息
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);
socket.SendTo(Encoding.UTF8.GetBytes("客户端的消息"), remotePoint);
//收消息
byte[] bytes = new byte[512];
EndPoint receivePoint = new IPEndPoint(IPAddress.Any, 0);
int len = socket.ReceiveFrom(bytes,ref receivePoint);
print((receivePoint as IPEndPoint).Address.ToString() + "发来了:" + Encoding.UTF8.GetString(bytes,0,len));
//关闭
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
演示结果
文章来源地址https://www.toymoban.com/news/detail-764440.html
到了这里,关于Unity实现网络通信(UDP)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!