Unity Sockets communication uses the UDP protocol, set the client computer network configuration, use new threads to obtain data, and solve the stuck problem.

Debugging and connecting to the server today, I found that the data of the server is still not available.
The computer and the server are both in the same LAN, but still cannot be obtained.
The following is the configuration of the computer environment.
The first step:
set the network as a private network, and then click Configure Firewall and Security Settings, turn off the firewall
(click the properties of the connected wifi)
insert image description here

Step 2: Set outbound and inbound rules
Click Advanced Settings, Inbound Rules—Create: Select Port—Select UDP, All Local Ports, – Allow Connections—Check all three—give a name such as UDP Connection Outbound Rules
and The steps for inbound rules are the same

insert image description here

insert image description here

Now run to see if the server data can be obtained,

If you haven’t obtained it yet, you need to set your own IP address as fixed,
insert image description here
then click Details, take a photo and remember the IPV4 address and IPV4 subnet mask. IPv4 Gateway, then close
click Properties
insert image description here

Fill in the settings by pressing the things recorded just now,
insert image description here

//然后在Sockets 通信代码中 绑定的IP 使用自己的IP,
 IPAddress ipAddress = IPAddress.Parse("自己电脑的IP");

When the UDP code is below

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.UI;



public class ClientHandlerUDP : MonoBehaviour
{
    
    
   

    IPAddress ipAddress;
    private const int Port = 服务器端口号;
    static Socket receiverSocket;
    static EndPoint remoteEndPoint;

    Thread thread;
    public void Start()
    {
    
    

         设置服务器IP和端口

        string json = CreatFile(Application.streamingAssetsPath + "/IP", "IP.json");//IP地址放到了一个json文件里,方便在其他电脑上配置
        IPClass ip = JsonUtility.FromJson<IPClass>(json);
        
         ipAddress = IPAddress.Parse(ip.ip);
        Debug.Log($"IP和端口号,ip{
      
      ip.ip},,,端口号:{
      
      Port}");

        StartUpd();


    }
    public void StartUpd()
    {
    
    

        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port);
        remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
        try
        {
    
    
            Debug.Log("创建UDP Socket");
            // 创建UDP Socket
            receiverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


            Debug.Log($"绑定IP和端口号");
            // 将Socket绑定到本地IP和端口
            receiverSocket.Bind(localEndPoint);
            thread = new Thread(ThreadUpdate);//使用新线程,可以有效防止 获取数据时 运行太卡的问题,
            thread.Start();

            Debug.Log("UDP接收器已启动,等待接收消息...");



        }
        catch (Exception ex)
        {
    
    
            Debug.Log(string.Format("发生异常: {0}", ex.Message));
        }
    }


    bool isThreadRunning = true;
    public void ThreadUpdate()
    {
    
    
        if (isThreadRunning)
        {
    
    
            Debug.Log("线程开启");
            while (true)
            {
    
    
                byte[] buffer = new byte[1024];
                Debug.Log("准备接收消息");
                int bytesRead = receiverSocket.ReceiveFrom(buffer, ref remoteEndPoint);

                string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);

                Debug.Log(string.Format("接收到来自 {0} 的消息: {1}", remoteEndPoint.ToString(), message));
               
                Thread.Sleep(1000);
            }
        }

    }
    // 关闭新线程
    private void StopThread()
    {
    
    
        // 在主线程中修改标志变量的值
        isThreadRunning = false;
        if (thread == null) return;
        // 等待新线程结束
        thread.Abort();
    }
    public void OnDisable()
    {
    
    
        StopThread();
    }
    private string CreatFile(string filePath, string fileName)
    {
    
    
        string fullPath = Path.Combine(filePath, fileName);
        if (!Directory.Exists(filePath))
        {
    
    
            Directory.CreateDirectory(filePath);
        }
        if (!File.Exists(fullPath))
        {
    
    
            FileStream fs1 = new FileStream(fullPath, FileMode.Create);
            fs1.Flush();
            fs1.Close();
        }

        byte[] byets = File.ReadAllBytes(fullPath);
        return Encoding.UTF8.GetString(byets);
    }
}
[Serializable]
public class IPClass
{
    
    
    public string ip;
}

Guess you like

Origin blog.csdn.net/o_ojjj/article/details/131014407