?Unity 搭建UDP客户端(01) 配合网络调试助手测试

2023-12-14 15:40:17

1.接收来自服务器的消息

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

public class UDPManager:MonoBehaviour
{
    public string recvStr; //服务器返回值
    public string UDPClientAddRess = "192.168.2.39"; //目标服务器地址
    public int UDPClientPort = 8080; //目标服务器端口号
    Socket socket;
    EndPoint serverEnd;
    IPEndPoint ipEnd;
    byte[] recvData = new byte[1024];
    byte[] sendData = new byte[1024];
    int recvLen = 0;
    Thread connectThread;
    /// <summary>
    /// 想服务器发送数据
    /// </summary>
    /// <param name="message"></param>
    public void InitSocket(string message)
    {
        Debug.Log(message);
        UDPClientAddRess = UDPClientAddRess.Trim();
        ipEnd = new IPEndPoint(IPAddress.Parse(UDPClientAddRess), UDPClientPort);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        serverEnd = sender;
        Debug.Log("等待链接");
        SocketSend(message);
        Debug.Log("连接成功");
        connectThread = new Thread(new ThreadStart(SocketReceve));
        connectThread.Start();
    }
    /// <summary>
    /// 想服务端发送需要发送的内容
    /// </summary>
    /// <param name="sendMessage"></param>
    public void SocketSend(string sendMessage)
    {
        //首先清空所有
        sendData = new byte[1024];
        //转换数据
        sendData = Encoding.UTF8.GetBytes(sendMessage);
        //将数据发送到服务端
        socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEnd);
    }
    /// <summary>
    /// 接收来自服务端的消息
    /// </summary>
    void SocketReceve()
    {
        while (true)
        {
            recvData = new byte[1024];
            try
            {
                recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
            }
            catch (System.Exception e)
            {
                Debug.LogError("出现异常,异常信息:" + e);
            }
            Debug.Log("收到信息,信息来自:" + serverEnd.ToString());
            if (recvLen > 0)
            {
                recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
               
                Debug.Log(recvStr);
               
            }
            else
            {
                Debug.LogError("出现错误,请检查网络链接是否正常");
            }
        }
    }

    /// <summary>
    /// 关闭与服务器的连接
    /// </summary>
    public void SocketQuit()
    {
        //如果线程还在就需要关闭线程
        Debug.Log("销毁UDP");
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
        {
            socket.Close();
        }
    }
}

2.给服务器发送消息

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