在开发过程中,我们经常会遇到网络通讯的问题,对于一些实验性系统的调试、控制、状态传送还都是挺有帮助的,这里记录一下UDP的基础代码,如果作为服务器的话,可能还需要额外处理回复目标的逻辑(比如记录消息来源的清单等),这里就比较单纯的整理了一下,有需要的可以取用。
需要注意,消息的编码可能影响不同的语言,对于中文等可能需要对应修改。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class UDPNetwork : MonoBehaviour
{
private int _localPort = 0;//本地端口,IP默认本地IP
private int _remotePort = 0;//远端端口与IP地址
private string _remoteIP="127.0.0.1";
private UdpClient udpClient = null;
public delegate void NetworkMessageEventHandler(string msg, int port, string IP);
public event NetworkMessageEventHandler OnReceiveNetworkMessage;//通过此事件接收到消息做后续处理
public event NetworkMessageEventHandler OnSendNetworkMessage;//通过此事件广播发送的消息内容,以便做后续处理
// Start is called before the first frame update
void Start()
{
//如果不希望在本脚本的接收回调或者发送回调中处理数据,可以绑定相应事件进行处理,其他脚本绑定事件时要先找到本对象
//例如:FindObjectOfType<UDPNetwork>().OnReceiveNetworkMessage
//具体要看有几个实例采取不同的操作
this.OnReceiveNetworkMessage += ReceiveMsgDebugLog;
this.OnSendNetworkMessage += SendMsgDebugLog;
SetupUDP(10250, "127.0.0.1", 2050);//自己调用也行,外部调用也行
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.Space))
SendUdpMessage("space pressed");
if (Input.GetKeyUp(KeyCode.Return))
SendUdpMessage("Return Pressed", _remoteIP, _remotePort == 2050 ? 2051 : 2050);
}
/// <summary>
/// 使用本函数创建客户端
/// </summary>
/// <param name="localPort"></param>
/// <param name="remoteIP"></param>
/// <param name="remotePort"></param>
public void SetupUDP(int localPort, string remoteIP, int remotePort)
{
CreateClient(localPort);
_remoteIP=remoteIP;
_remotePort=remotePort;
}
/// <summary>
/// 根据SetTarget函数的设定,创建客户端并开始监听接收消息
/// </summary>
private void CreateClient(int port)
{
udpClient = new UdpClient(port);
udpClient?.BeginReceive(ReceiveCallBack, null);
}
/// <summary>
/// 发送消息到设定的IP与端口,默认到上一个目标
/// </summary>
/// <param name="msg">消息文本</param>
public void SendUdpMessage(string msg)
{
SendUdpMessage(msg, _remoteIP, _remotePort);
}
/// <summary>
/// 发送消息到本函数指定的IP与端口
/// </summary>
/// <param name="msg">消息文本</param>
/// <param name="rIP">目标IP</param>
/// <param name="rPort">目标端口</param>
public void SendUdpMessage(string msg, string rIP, int rPort)
{
byte[] bytes = Encoding.UTF8.GetBytes(msg);
_remoteIP = rIP;
_remotePort = rPort;
udpClient?.BeginSend(bytes, bytes.Length, rIP, rPort, SendCallBack, null);
OnSendNetworkMessage?.Invoke(msg,rPort,rIP);
}
/// <summary>
/// 异步接收消息回调
/// </summary>
/// <param name="ar"></param>
private void ReceiveCallBack(IAsyncResult ar)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udpClient?.EndReceive(ar, ref remoteEndPoint);
string msg = Encoding.UTF8.GetString(data);
//Debug.Log($"From {remoteEndPoint.Address.ToString()}:{remoteEndPoint.Port} Get Message : {msg}");
udpClient?.BeginReceive(ReceiveCallBack, null);
OnReceiveNetworkMessage?.Invoke(msg,remoteEndPoint.Port,remoteEndPoint.Address.ToString());
}
/// <summary>
/// 异步发送消息回调
/// </summary>
/// <param name="ar"></param>
private void SendCallBack(IAsyncResult ar)
{
if (udpClient.EndSend(ar) == 0)
{
Debug.LogError("SendError");
}
}
/// <summary>
/// 程序退出时记得关闭socket释放端口资源
/// </summary>
private void OnApplicationQuit()
{
udpClient?.Close();
}
private void ReceiveMsgDebugLog(string msg, int port, string IP)
{
Debug.Log($"Receive Message [{msg}] from {IP}:{port}");
}
private void SendMsgDebugLog(string msg, int port, string IP)
{
Debug.Log($"Send Message [{msg}] to {IP}:{port}");
}
}