ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

UDP简单的接收和发送

2026/8/30 3:13:50 拓冰建站 浏览量
UDP简单的接收和发送

注释

udp简单的接收和发送,不分服务器和客户端,代码都一样,可以通用

using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;public class UDPManager
{/// <summary>/// 客户端/// </summary>private UdpClient udpClient;/// <summary>/// 做发送时使用/// </summary>private IPEndPoint sendEndPoint;/// <summary>/// 接收任何IP消息/// </summary>private IPEndPoint anyIP;#region UDP发送消息/// <summary>/// 发送端初始化/// </summary>/// <param name="ipAddress">IP地址</param>/// <param name="port">端口</param>public UDPManager(string ipAddress, int port){udpClient = new UdpClient();sendEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);}/// <summary>/// 发送消息/// </summary>/// <param name="message">信息</param>public void SendData(string message){byte[] data = System.Text.Encoding.UTF8.GetBytes(message);udpClient.Send(data, data.Length, sendEndPoint);}#endregion#region UDP收消息/// <summary>/// 接收端初始化/// </summary>/// <param name="port">端口</param>public UDPManager(int port){udpClient = new UdpClient(port);anyIP = new IPEndPoint(IPAddress.Any, 0);udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);}/// <summary>/// 接收消息/// </summary>/// <param name="ar"></param>private void ReceiveCallback(IAsyncResult ar){byte[] data = udpClient.EndReceive(ar, ref anyIP);string message = System.Text.Encoding.UTF8.GetString(data);Debug.Log("Received message: " + message);udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);}#endregionpublic void Close(){udpClient.Close();}
}