UDP简单的接收和发送

using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

public class UDPManager
{
    /// 
    /// 客户端
    /// 
    private UdpClient udpClient;
    /// 
    /// 做发送时使用
    /// 
    private IPEndPoint sendEndPoint;
    /// 
    /// 接收任何IP消息
    /// 
    private IPEndPoint anyIP;


    #region UDP发送消息
    /// 
    /// 发送端初始化
    /// 
    /// IP地址
    /// 端口
    public UDPManager(string ipAddress, int port)
    {
        udpClient = new UdpClient();
        sendEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
    }

    /// 
    /// 发送消息
    /// 
    /// 信息
    public void SendData(string message)
    {
        byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
        udpClient.Send(data, data.Length, sendEndPoint);
    }
    #endregion



    #region UDP收消息
    /// 
    /// 接收端初始化
    /// 
    /// 端口
    public UDPManager(int port)
    {
        udpClient = new UdpClient(port);
        anyIP = new IPEndPoint(IPAddress.Any, 0);
        udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);
    }
    /// 
    /// 接收消息
    /// 
    /// 
    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);
    }

    #endregion

    public void Close()
    {
        udpClient.Close();
    }
}

你可能感兴趣的:(udp,网络协议,unity,c#)