unity 接收和发送Udp消息

因为需要用到unity和其他的程序交互,其他程序可以提供Udp消息,因此找了合适的相互连接方法。这里直接上代码。

工具类:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.Video;

public class UdpManager
{
    public static string m_receivedMessage;
    static IPEndPoint m_IPEndPoint;
    static UdpClient m_udpClient;


    public static void InitializeUdpClient()
    {
        m_IPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
        m_udpClient = new UdpClient(m_IPEndPoint);
        UdpModel s = new UdpModel(m_udpClient, m_IPEndPoint);
        m_udpClient.BeginReceive(EndReceive, s);
        Debug.Log("服务器启动");

    }

    //结束得到的信息
    private static void EndReceive(IAsyncResult ar)
    {
        try
        {
            UdpModel m_UdpModel = ar.AsyncState as UdpModel;
            if (m_UdpModel != null)
            {
                UdpClient udpClient = m_UdpModel.m_udpclient;
                IPEndPoint ip = m_UdpModel.m_ip;
                Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip);
                string msg = Encoding.UTF8.GetString(receiveBytes);
                m_receivedMessage = msg;
                udpClient.BeginReceive(EndReceive, m_UdpModel); //开始获取

            }
        }
        catch (Exception ex)
        {
            //处理异常
        }
    }

    //udp模型
    private class UdpModel
    {
        public UdpClient m_udpclient = null;
        public IPEndPoint m_ip;
        public UdpModel(UdpClient udpclient, IPEndPoint ip)
        {
            this.m_udpclient = udpclient;
            this.m_ip = ip;
        }
    }

    //关闭
    public static void Close()
    {
        if (m_udpClient != null)
        {
            m_udpClient.Close();
            m_udpClient = null;
        }
    }

    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="obj"></param>
    public static void SendMessage(string message)
    {
        UdpClient myUdpClient = new UdpClient();
        IPEndPoint endpoint;
        //当前服务器ip和端口号
        myUdpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 8800));

        //要发送给的地址和端口号,255.255.255.255表示在这个局域网的所有ip
        endpoint = new IPEndPoint(IPAddress.Parse("192.168.31.174"), 1180);

        byte[] bytes = Encoding.UTF8.GetBytes(message);
        try
        {
            myUdpClient.Send(bytes, bytes.Length, endpoint);
            myUdpClient.Close();
        }
        catch (Exception err)
        {
            Console.Write(err.Message, "发送失败");
        }
        finally
        {
            myUdpClient.Close();
        }
    }
}

需要挂载运行的脚本:

using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Video;

/// <summary>
/// 服务接收生成
/// </summary>
public class ServerControl : MonoBehaviour
{
    
   
 
    void Start()
    {

        UdpManager.InitializeUdpClient();

        //part1Root.SetActive(true);
        //part2Root.SetActive(false);
    }
    void Update()
    {

        if (UdpManager.m_receivedMessage != null)
        {
            string[] array = UdpManager.m_receivedMessage.Split(',');
            Debug.Log(UdpManager.m_receivedMessage);
          
            UdpManager.m_receivedMessage = null;
        
        }
      


    }

    private void OnDestroy()
    {
        UdpManager.Close();
    }
}

使用方法很简单,把ServerControl脚本挂载在一个物体上,直接运行即可,接受信息的方法和发送的方法都在两个脚本里。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在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函数会被自动调用,你可以在这个函数中处理接收到的消息

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值