Unity simple UDP communication


Advantages of UDP communication

The advantage of UDP communication is that it does not require the other party to be forced to be online, and there is no jamming problem caused by poor network connection or connection failure; the disadvantage is also that the entire connection is unreliable because it cannot be judged whether the other party is online, and feedback is required through custom code.

Use of UDP

The following code is a simple UDP communication base class. After inheriting this class, you need to call the InitSocket method to initialize before it can be used. The reason why there is no direct initialization here is that it may be necessary to modify the port number or perform initialization after other settings, so initialization Operations are performed in subclasses.
After the initialization is complete, you can send messages through SendMessage , get the received messages through DequeueData , and check the number of unprocessed messages through DequeueDataCount , so as to realize a simple UDP communication.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

public class UDPBase : MonoBehaviour
{
    
    

    protected int localPort = 54321;      //本地端口
    protected int sendPort = 12345;       //接收端的端口

    private Socket serverSocket;        //Socket对象用于创建本地UDP通道
    private static UdpClient client;    //UdpClient对象,用于与接收端通信
    private EndPoint clientEndPoint;    //用于承载发送消息的服务器的EndPoint信息
    private byte[] ReceiveData = new byte[1024];    //创建数据缓冲区,用于接收发送来的数据
    private Queue<byte[]> dataQueue = new Queue<byte[]>();  //接收数据队列,存入原始数据,特性:先入先出


    /// <summary>
    /// 初始化Socket
    /// </summary>
    protected void InitSocket()
    {
    
    
        //实例化UDP服务器的Socket通道
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //Socket绑定IP和端口
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, localPort));
        clientEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
        //开始异步接收数据
        serverSocket.BeginReceiveFrom(ReceiveData, 0, ReceiveData.Length, 
            SocketFlags.None, ref clientEndPoint, new AsyncCallback(ReceiveMessageToQueue), clientEndPoint);

        client = new UdpClient();

    }

    /// <summary>
    /// 接收消息并存放 
    /// </summary>
    /// <param name="iar"></param>
    private void ReceiveMessageToQueue(IAsyncResult iar)
    {
    
    
        int receiveDataLength = serverSocket.EndReceiveFrom(iar, ref clientEndPoint);

        //继续监听
        serverSocket.BeginReceiveFrom(ReceiveData, 0, ReceiveData.Length,
            SocketFlags.None, ref clientEndPoint, new AsyncCallback(ReceiveMessageToQueue), clientEndPoint);

        if (receiveDataLength > 0)
        {
    
    
            byte[] data = new byte[receiveDataLength];
            Buffer.BlockCopy(ReceiveData,0, data,0, receiveDataLength);
            dataQueue.Enqueue(data);
        }

    }

    /// <summary>
    /// 从队列中取出数据
    /// </summary>
    /// <returns></returns>
    protected byte[] DequeueData()
    {
    
    
       return dataQueue.Dequeue();
    }

    protected int DequeueDataCount
    {
    
    
        get {
    
     return dataQueue.Count; }
    }



    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="ipEndPoint"></param>
    /// <param name="sendData"></param>
    protected void SendMessage(IPEndPoint ipEndPoint, byte[] sendData)
    {
    
    
        client.Send(sendData, sendData.Length, ipEndPoint);
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="ipEndPoint"></param>
    /// <param name="sendStr"></param>
    protected void SendMessage(IPEndPoint ipEndPoint, string sendStr)
    {
    
    
        byte[] sendData = System.Text.Encoding.UTF8.GetBytes(sendStr);
        SendMessage(ipEndPoint, sendData);
    }


    /// <summary>
    /// 关闭Socket
    /// </summary>
    public void SocketQuit()
    {
    
    
        if (serverSocket != null)
        {
    
    
            serverSocket.Close();
        }
    }


    /// <summary>
    /// 当关闭此对象时关闭Socket
    /// </summary>
    private void OnDestroy()
    {
    
    
        SocketQuit();
    }


}

Guess you like

Origin blog.csdn.net/qq_27050589/article/details/128411961