unity 接收和发送Udp消息

news/2024/5/18 13:00:10 标签: 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脚本挂载在一个物体上,直接运行即可,接受信息的方法和发送的方法都在两个脚本里。


http://www.niftyadmin.cn/n/5165584.html

相关文章

Git 入门使用 —— 建库、代码上下传、常用命令

目录 一、Git 入门 1.1 Git简介 1.2 Git安装 1.3 创建码云仓库 二、Git 使用 2.1 git初始化操作 2.2 代码上传 2.3 代码下载 2.4 代码更新 2.4.1 仓库管理者 2.4.1 仓库使用者 三、Git 常用命令 一、Git 入门 1.1 Git简介 Git是一个开源的分布式版本控制系统&am…

C++ 输入、输出和整数运算

【问题描述】 编写一个程序&#xff0c;读入两个整数&#xff0c;计算并输出他们的和、积、商和余数。 【输入形式】 程序运行到输入时&#xff0c;不要显示输入提示信息。 输入为两个整数&#xff08;在问题描述中记作A和B&#xff0c;程序中请自定变量名&#xff09;,A和B使…

el-table实现单选框+隐藏多选框+回显

0 效果 1 单选框 2 隐藏多选框 3 回显 回显数据要在el-table中添加两个属性

福州湾107㎡三室两厅两卫,温柔如风的奶油原木风,自由浪漫的灵魂。福州中宅装饰,福州装修

今天要分享的是一套面积107平米的奶油原木风三室两厅的案例。设计师于业主诉求中抽丝剥茧&#xff0c;汲取灵感&#xff0c;以大热的现代风格为主&#xff0c;暖色为主基调&#xff0c;配合原木肌理和巧思的质感细节装饰&#xff0c;最终打造出一种自由与惬意的空间。 01丨业 主…

JS点击图片指定对象变色两种方法

要求&#xff1a;点击上面的颜色实现下面的图像变成相同的颜色 难点&#xff1a;对于js函数的this对象不太清楚如何传递 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>changeColor</title>&l…

算法设计与分析 | 循环赛

题目设有n2k个球队参加循环赛&#xff0c;要求设计一个满足以下要求比赛日程表&#xff1a; (1) 每支球队必须与其他n-1支球队各赛一次&#xff1b; (2) 每支球队一天只能参赛一次&#xff1b; (3) 循环赛在n-1天内结束。 输入 一个整数k&#xff08;0 < k < 6&#…

小白高效自学-网络安全(黑客技术)

网络安全零基础入门学习路线&规划 初级 1、网络安全理论知识&#xff08;2天&#xff09; 了解行业相关背景&#xff0c;前景&#xff0c;确定发展方向。 学习网络安全相关法律法规。 网络安全运营的概念。 等保简介、等保规定、流程和规范。&#xff08;非常重要&#x…

《面纱》细嚼的句子

记住&#xff0c;履行职责并不值得称道 因为那是你应该做的&#xff0c;就像手脏了该洗手一样。唯有一点颇为重要&#xff0c;那就是爱你的职责。当爱和职责合而为一时&#xff0c;上天就会降恩典于你&#xff0c;让你享受到你连想都不敢想的无边的幸福。——《面纱》 所谓“道…