unity UDP广播 用于Windows和Android
using System.Net.Sockets; using System.Net; using UnityEngine; using System.Text; public class SocketUDP : MonoBehaviour { private Socket socket; private IPEndPoint ipEnd; private byte[] data; public int udpPort = 9050; public static SocketUDP instance; public GameObject obj; public void Awake() { EventTriggerListener.Get(obj).onClick = onClick; if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); BroadcastIP(); } else { Destroy(gameObject); return; } } private void onClick(GameObject sender) { Send("123213"); } public void BroadcastIP() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); ipEnd = new IPEndPoint(IPAddress.Broadcast, udpPort); data = Encoding.ASCII.GetBytes("111"); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); Send("hello"); } public void Send(string msg) { Debug.Log("发送消息:" + msg); data = Encoding.ASCII.GetBytes(msg); socket.SendTo(data, ipEnd); } private void OnApplicationQuit() { print("关闭"); socket.Shutdown(SocketShutdown.Both); socket.Close(); } }
posted on 2022-11-15 15:58 zqiang0803 阅读(189) 评论(0) 编辑 收藏 举报