1 using System.Collections.Generic; 2 using System.Net; 3 using System.Net.Sockets; 4 using System.Text; 5 using System.Threading; 6 using UnityEngine; 7 using System; 8 9 public class UDPClient2Client : MonoBehaviour 10 { 11 public static UDPClient2Client Instance = null; 12 private UdpClient client; 13 private Thread thread = null; 14 private IPEndPoint remotePoint; 15 public string ip="127.0.0.1"; 16 private int port = 9090; 17 18 public Action<string> receiveMsg = null; 19 20 private string receiveString = null; 21 void Awake() 22 { 23 if (Instance == null) 24 { 25 Instance = this; 26 DontDestroyOnLoad(gameObject); 27 } 28 else 29 { 30 Destroy(gameObject); 31 } 32 } 33 // Use this for initialization 34 void Start() 35 { 36 37 38 39 // ip = IPManager.ipAddress; 40 remotePoint = new IPEndPoint(IPAddress.Any, 0); 41 thread = new Thread(ReceiveMsg); 42 thread.Start(); 43 } 44 //接受消息 45 void ReceiveMsg() 46 { 47 while (true) 48 { 49 client = new UdpClient(port); 50 51 byte[] receiveData = client.Receive(ref remotePoint);//接收数据 52 receiveString = Encoding.UTF8.GetString(receiveData); 53 54 client.Close(); 55 } 56 } 57 //发送消息 58 void SendMsg(IPAddress ip, string _msg) 59 { 60 IPEndPoint remotePoint = new IPEndPoint(ip, port);//实例化一个远程端点 61 62 if (_msg != null) 63 { 64 byte[] sendData = Encoding.Default.GetBytes(_msg); 65 UdpClient client = new UdpClient(); 66 client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点 67 client.Close();//关闭连接 68 } 69 } 70 // Update is called once per frame 71 void Update() 72 { 73 if (!string.IsNullOrEmpty(receiveString)) 74 { 75 76 //消息处理 77 if (receiveMsg != null && remotePoint.Address.ToString() != ip) 78 { 79 Debug.Log(remotePoint.Address + ":" + remotePoint.Port + " ---> " + receiveString); 80 receiveMsg.Invoke(receiveString); 81 receiveString = null; 82 83 } 84 } 85 86 } 87 void OnDestroy() 88 { 89 SocketQuit(); 90 } 91 void SocketQuit() 92 { 93 thread.Abort(); 94 thread.Interrupt(); 95 client.Close(); 96 } 97 void OnApplicationQuit() 98 { 99 SocketQuit(); 100 } 101 102 103 104 105 }
接受消息添加委托
void Start() { UDPClient2Client.Instance.receiveMsg = Rstring;
} void Rstring(string str) { Debug.Log(str); }
//发送消息 参数
SendMsg(IPAddress.Parse(“127.0.0.1”), “发送”);
原文:https://www.cnblogs.com/G993/p/11678934.html