转载自 Unity3D使用UDP协议实现两个程序传递信息
这里记录一下注意点
这里用的是内网的ip地址
如何在win10下查看自己电脑的内网IP地址
端口随意,两个程序的端口相同就行了,我试了两个,24和112
下面的红框注意一致
UDP Send
UDP Receive
主要代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; public class UDPSend: MonoBehaviour { private string ip = "192.168.0.77"; //主机ip地址 private IPAddress ipAddress; private IPEndPoint endPoint; private Socket socket; private EndPoint server; private byte[] sendData; //发送内容,转化为byte字节 //发送函数 public void Send(int value) //参数不是字符串时转化为string { string msg = value.ToString(); //传递的值转化为string try { ipAddress = IPAddress.Parse(ip); //ip地址 endPoint = new IPEndPoint(ipAddress, 112); //自定义端口号 socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 112); server = (EndPoint)sender; sendData = new byte[1024]; //定义发送字节大小 sendData = Encoding.Default.GetBytes(msg); //对msg编码 socket.SendTo(sendData, sendData.Length, SocketFlags.None, endPoint); //发送信息 } catch { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; using UnityEngine.UI; public class UDPReceive: MonoBehaviour { //public LeaderControll leaderControll; //外面要使用接收到信息的类 private IPEndPoint ipEndPoint; private Socket socket; private Thread thread; private byte[] bytes; //接收到的字节 private int bytesLength; //长度 private string receiveMsg=""; //接收到的信息 [SerializeField] private Text resultText; void Start() { Init(); } //初始化 private void Init() { ipEndPoint = new IPEndPoint(IPAddress.Any, 112); //端口号要与发送端一致 socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(ipEndPoint); thread = new Thread(new ThreadStart(Receive)); //开启一个线程,接收发送端的消息 thread.IsBackground = true; thread.Start(); } //接收消息函数 private void Receive() { // IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 112); EndPoint remote = (EndPoint)sender; while (true) { bytes = new byte[1024]; bytesLength = socket.ReceiveFrom(bytes, ref remote); receiveMsg = Encoding.ASCII.GetString(bytes, 0, bytesLength); } } //实时接收消息 void Update() { // if (receiveMsg != "") // { // // leaderControll.Goto(receiveMsg); //外部使用接收到的字符串 // receiveMsg = ""; // } if (receiveMsg != "") { print(" " +receiveMsg); resultText.text = receiveMsg; } } //关闭socket,关闭thread private void OnDisable() { if (socket != null) { socket.Close(); } if (thread != null) { thread.Interrupt(); thread.Abort(); } } }