因为需要用到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;
- }
- }
-
- ///
- /// 发送数据
- ///
- ///
- 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;
-
- ///
- /// 服务接收生成
- ///
- 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脚本挂载在一个物体上,直接运行即可,接受信息的方法和发送的方法都在两个脚本里。