UDP异步发送与接收

直接上代码

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

/// <summary>
/// UDP协议异步通讯类(服务器端)
/// </summary>
public class UDPServer
{

    /// <summary>
    /// 容器对象
    /// </summary>
    public class UDPServerState
    {
        //服务器端
        public Socket UDPServer
        {
            get;
            set;
        }
        //接受数据缓冲区
        private byte[] m_receiveBuffer = new byte[1024];
        public byte[] ReceiveBuffer
        {
            get
            {
                return m_receiveBuffer;
            }
        }

        //远程终端
        public EndPoint m_remoteEP;

        public void ClearReceiveBuffer()
        {
            for (int i = 0; i < 1024; i++)
            {
                ReceiveBuffer[i] = 0;
            }
        }
    }

    public UDPServerState ServerState
    {
        get;
        set;
    }


    /// <summary>
    /// 服务器绑定终端节点
    /// </summary>
    public void ServerBind()
    {
        //主机IP
        IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
        Socket UDPServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        UDPServer.Bind(serverEP);
        Debug.Log("server ready...");
        
        ServerState = new UDPServerState();
        ServerState.UDPServer = UDPServer;
        ServerState.m_remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
        AsyncRecive();
    }

    /// <summary>
    /// 异步接受消息
    /// </summary>
    public void AsyncRecive()
    {
        ServerState.ClearReceiveBuffer();
        ServerState.UDPServer.BeginReceiveFrom(ServerState.ReceiveBuffer, 0, ServerState.ReceiveBuffer.Length, SocketFlags.None, ref ServerState.m_remoteEP,
            new AsyncCallback(ReciveCallback), null);
    }


    /// <summary>
    /// 异步接受消息回调函数
    /// </summary>
    /// <param name="asyncResult"></param>
    public void ReciveCallback(IAsyncResult asyncResult)
    {
        if (asyncResult.IsCompleted)
        {
            try
            {
                //获取发送端的终节点
                ServerState.m_remoteEP = new IPEndPoint(IPAddress.Any, 0);
                int charactorsCount = ServerState.UDPServer.EndReceiveFrom(asyncResult, ref ServerState.m_remoteEP);

                string base64string = Encoding.ASCII.GetString(ServerState.ReceiveBuffer);
               
            }
            catch (Exception e)
            {
                Debug.Log("服务端接收数据出错:" + e);
            }
            finally
            {
                //继续接受消息
                AsyncRecive();
            }
        }
        else
        {
            Debug.Log("服务端接收数据失败");
            //继续接受消息
            AsyncRecive();
        }
    }

    /// <summary>
    /// 异步发送消息
    /// </summary>
    /// <param name="message"></param>
    public void AsyncSend(string message)
    {
        Debug.Log("server-->-->client:" + message);
        byte[] buffer = Encoding.UTF8.GetBytes(message);

        ServerState.UDPServer.BeginSendTo(buffer, 0, buffer.Length, SocketFlags.None, ServerState.m_remoteEP),
            new AsyncCallback(SendCallback), null);
    }

    /// <summary>
    /// 异步发送消息回调函数
    /// </summary>
    /// <param name="asyncResult"></param>
    public void SendCallback(IAsyncResult asyncResult)
    {
        //消息发送完毕
        if (asyncResult.IsCompleted)
        {
            ServerState.UDPServer.EndSendTo(asyncResult);
            Debug.Log("服务端发送数据完成");
        }
        else
        {
            Debug.Log("服务端发送数据失败");
        }
    }

    //连接关闭
    public void SocketQuit()
    {
        
        //最后关闭socket
        if (ServerState.UDPServer != null)
            ServerState.UDPServer.Close();
       
    }

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Unity中实现UDP广播的发送接收,可以使用C#中的Socket类,以下是一个示例代码: ```csharp using System.Net; using System.Net.Sockets; using System.Text; public class UdpBroadcastSender : MonoBehaviour { private const int PORT = 12345; private UdpClient udpClient; private void Start() { udpClient = new UdpClient(); udpClient.EnableBroadcast = true; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, PORT)); } private void OnDestroy() { udpClient.Close(); } public void SendMessage(string message) { byte[] data = Encoding.ASCII.GetBytes(message); udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, PORT)); } } public class UdpBroadcastReceiver : MonoBehaviour { private const int PORT = 12345; private UdpClient udpClient; private IPEndPoint ipEndPoint; private void Start() { udpClient = new UdpClient(PORT); ipEndPoint = new IPEndPoint(IPAddress.Any, PORT); udpClient.EnableBroadcast = true; udpClient.MulticastLoopback = true; udpClient.JoinMulticastGroup(IPAddress.Broadcast); udpClient.BeginReceive(new AsyncCallback(OnReceive), null); } private void OnDestroy() { udpClient.Close(); } private void OnReceive(IAsyncResult result) { byte[] data = udpClient.EndReceive(result, ref ipEndPoint); string message = Encoding.ASCII.GetString(data); Debug.Log("Received message: " + message); udpClient.BeginReceive(new AsyncCallback(OnReceive), null); } } ``` 在以上代码中,UdpBroadcastSender类用来发送UDP广播消息,UdpBroadcastReceiver类用来接收UDP广播消息。在UdpBroadcastReceiver类中,我们使用了异步回调的方式来接收消息,这样可以保证在接收到消息之前不会阻塞主线程。 在Unity中,你可以将上述代码分别添加到两个不同的GameObject上,并在需要发送广播消息的时候调用UdpBroadcastSender.SendMessage函数即可。同时,在接收到广播消息时,UdpBroadcastReceiver.OnReceive函数会被自动调用,你可以在这个函数中处理接收到的消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值