客户端在上一篇
由于服务器逻辑写的较为简单
所以直接上代码了~
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;public class UdpServer : MonoBehaviour
{public static UdpServer instance;private void Awake(){if (instance != null){return;}else{instance = this;}}public int serverPort = 8080;private UdpClient udpServer;private void Start(){udpServer = new UdpClient(serverPort);udpServer.BeginReceive(ReceiveCallback, null);}private IPEndPoint Clientip;private void ReceiveCallback(IAsyncResult result){try{IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, serverPort);byte[] receivedBytes = udpServer.EndReceive(result, ref clientEndPoint);string receivedMessage = Encoding.ASCII.GetString(receivedBytes);Clientip = clientEndPoint;Debug.Log("收到来自客户端的消息: " + receivedMessage + "-----" + clientEndPoint);// 继续接收下一个消息udpServer.BeginReceive(ReceiveCallback, null);}catch (Exception e){Debug.LogError("Error receiving UDP message: " + e.Message);}}public void SendBroadcastMessage(string message){// 发送广播消息IPEndPoint endPoint = Clientip;byte[] messageBytes = Encoding.ASCII.GetBytes(message);udpServer.Send(messageBytes, messageBytes.Length, endPoint);}private void OnDestroy(){if (udpServer != null){udpServer.Close();}}private void Update(){if (Input.GetKeyDown(KeyCode.K)){Debug.Log("发送");SendBroadcastMessage("hello client!");}}
}