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

客户端在上一篇

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

所以直接上代码了~

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值