⭐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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Unity中实现UDP广播的发送和接收,可以使用C#中的Socket类,以下是一个示例代码: ```csharp using System.Net; using System.Net.Sockets; using System.Text; public class UdpBroadcastSender : MonoBehaviour { private const int PORT = 12345; private UdpClient udpClient; private void Start() { udpClient = new UdpClient(); udpClient.EnableBroadcast = true; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, PORT)); } private void OnDestroy() { udpClient.Close(); } public void SendMessage(string message) { byte[] data = Encoding.ASCII.GetBytes(message); udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, PORT)); } } public class UdpBroadcastReceiver : MonoBehaviour { private const int PORT = 12345; private UdpClient udpClient; private IPEndPoint ipEndPoint; private void Start() { udpClient = new UdpClient(PORT); ipEndPoint = new IPEndPoint(IPAddress.Any, PORT); udpClient.EnableBroadcast = true; udpClient.MulticastLoopback = true; udpClient.JoinMulticastGroup(IPAddress.Broadcast); udpClient.BeginReceive(new AsyncCallback(OnReceive), null); } private void OnDestroy() { udpClient.Close(); } private void OnReceive(IAsyncResult result) { byte[] data = udpClient.EndReceive(result, ref ipEndPoint); string message = Encoding.ASCII.GetString(data); Debug.Log("Received message: " + message); udpClient.BeginReceive(new AsyncCallback(OnReceive), null); } } ``` 在以上代码中,UdpBroadcastSender类用来发送UDP广播消息UdpBroadcastReceiver类用来接收UDP广播消息。在UdpBroadcastReceiver类中,我们使用了异步回调的方式来接收消息,这样可以保证在接收消息之前不会阻塞主线程。 在Unity中,你可以将上述代码分别添加到两个不同的GameObject上,并在需要发送广播消息的时候调用UdpBroadcastSender.SendMessage函数即可。同时,在接收广播消息时,UdpBroadcastReceiver.OnReceive函数会被自动调用,你可以在这个函数中处理接收到的消息

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值