首页 > 解决方案 > 接收广播

问题描述

我已经测试了一个代码来接收广播消息,但它不起作用。这是代码:

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

public class SendReceiveRoomName : MonoBehaviour
{
    const int PORT_NO = 15000;
    private readonly UdpClient udpClient = new UdpClient();
    IPEndPoint ipendpointSend = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_NO);
    IPEndPoint ipendpointReceive = new IPEndPoint(IPAddress.Any, PORT_NO);
    IAsyncResult asyncResult = null;
    // Start is called before the first frame update
    void Start()
    {
        StartListening();
    }

    private void StartListening()
    {
        asyncResult = udpClient.BeginReceive(Receive, new object());
    }

    private void Receive(IAsyncResult asr)
    {
        ipendpointReceive = new IPEndPoint(IPAddress.Any, PORT_NO);
        byte[] bytes = udpClient.EndReceive(asr, ref ipendpointReceive);
        string message = Encoding.ASCII.GetString(bytes);
        Debug.Log("Received message:" + message);
        StartListening();
    }
}

此脚本附加到游戏对象。有人可以指出我的问题在哪里

标签: c#unity3d

解决方案


推荐阅读