在 做Socket通信時,了解了客戶端向服務器發送消息的
再來整理服務器向客戶端發送廣播消息
服務器端:
1 using UnityEngine; 2 using System.Collections; 3 using System.Net; 4 using System .Net.Sockets; 5 using System .Threading; 6 using System.Text; 7 8 9 /* 10 author:miss li 11 use for; 12 */ 13 namespace LMQ{ 14 public class Server : MonoBehaviour 15 { 16 Socket socket; 17 IPEndPoint ipEnd; 18 byte[] data; 19 string hostname; 20 21 void Init() 22 { 23 socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 24 ipEnd = new IPEndPoint (IPAddress.Broadcast, 8001); 25 hostname = Dns.GetHostName (); 26 data = Encoding.ASCII.GetBytes (hostname); 27 socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 28 Thread t = new Thread (BroadcastMessage); 29 t.Start (); 30 } 31 32 void Awake() 33 { 34 35 } 36 void Start () 37 { 38 Init (); 39 } 40 41 void BroadcastMessage() 42 { 43 while (true) { 44 // data = new byte[1024]; 45 // data = Encoding.ASCII.GetBytes (hostname); 46 socket.SendTo (data, ipEnd); 47 Thread.Sleep (2000); 48 49 50 51 } 52 } 53 54 void BroadcastMessage(string hostname) 55 { 56 while (true) { 57 data = new byte[1024]; 58 data = Encoding.ASCII.GetBytes (hostname); 59 socket.SendTo (data, ipEnd); 60 Thread.Sleep (2000); 61 } 62 63 } 64 //void OnGUI() 65 //{ 66 // hostname = GUI.TextField(new Rect(100, 50, 60, 30), hostname); 67 // if (GUI.Button(new Rect(100, 90, 60, 30), "send")) 68 // { 69 // BroadcastMessage(hostname); 70 // } 71 //} 72 73 74 } 75 }
客戶端:
using UnityEngine; using System.Collections; using System .Net; using System.Net.Sockets; using System .Threading; using System.Text; /* author:miss li use for; */ namespace LMQ{ public class Client : MonoBehaviour { Socket socket; IPEndPoint ipEnd; EndPoint End; byte[] data; int recv; string stringdata; void Init() { socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); ipEnd = new IPEndPoint (IPAddress.Any, 8001); socket.Bind (ipEnd); End = (EndPoint)ipEnd; Thread t = new Thread (ReceiveData); t.Start (); } void ReceiveData() { data = new byte[1024]; recv = socket.ReceiveFrom (data, ref End); stringdata = Encoding.ASCII.GetString (data, 0, recv); print ("received: " + stringdata + " form " + End.ToString ()); socket.Close (); } void Start () { Init (); } } }
當服務器端服務開啟之后,客戶端就會收到服務器端發送的廣播消息,
同樣的,服務端和客戶端的端口號都需要保持一致