?Unity 搭建UDP服务端(02)接收客户端消息

2023-12-14 17:11:29

客户端在上一篇

由于服务器逻辑写的较为简单

所以直接上代码了~

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!");
        }
    }
}

文章来源:https://blog.csdn.net/weixin_53501436/article/details/134859497
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。