⭐Unity 搭建UDP服务器(广播消息、接收客户端消息)

一、工程及代码

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class UdpServer : MonoBehaviour
{
    public int serverPort = 9999;
    public int broadcastPort = 8080;
    private UdpClient udpServer;
    private UdpClient udpBroadcastClient;

    private void Start()
    {
        udpServer = new UdpClient(serverPort);
        udpServer.BeginReceive(ReceiveCallback, null);

        udpBroadcastClient = new UdpClient();
        udpBroadcastClient.EnableBroadcast = true;
    }

    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);

            Debug.Log("收到来自客户端的消息: " + receivedMessage);

            if (receivedMessage.CompareTo("woaini")==0)
            {
                Debug.Log("对了");
            }

            // 继续接收下一个消息
            udpServer.BeginReceive(ReceiveCallback, null);
        }
        catch (Exception e)
        {
            Debug.LogError("Error receiving UDP message: " + e.Message);
        }
    }

    public void SendBroadcastMessage(string message)
    {
        IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Broadcast, broadcastPort);
        byte[] messageBytes = Encoding.ASCII.GetBytes(message);
        udpBroadcastClient.Send(messageBytes, messageBytes.Length, broadcastEndPoint);
    }

    private void OnDestroy()
    {
        if (udpServer != null)
        {
            udpServer.Close();
        }
        if (udpBroadcastClient != null)
        {
            udpBroadcastClient.Close();
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.K))
        {
            Debug.Log("发送");
            SendBroadcastMessage("hello client!");
        }
    }
}

二、配合网络调试助手使用

网络助手向服务器发送消息:

Unity UDP 广播消息:

三、调试助手下载地址

链接:https://pan.baidu.com/s/1az9ogJQrb4TqWK632cvCdw  密码:k6wp

猜你喜欢

转载自blog.csdn.net/weixin_53501436/article/details/134394018