实现客户端的网络不影响主线程且随时与服务器通信

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
//网络管理器(单例模式)
public class NetMgr : MonoBehaviour
{
    private static NetMgr instance;

    //用于发送消息的队列 公共容器 主线程往里边放 发送线程从里边取
    private Queue<string> sendMgsQueue = new Queue<string>();
    //用于接收消息的队列 公共容器 存放线程往里放 主线程从里边取
    private Queue<string> receiveMgsQueue = new Queue<string>(); 
    public static NetMgr Instance => instance;
    //用于收消息的水桶(容器)
    private byte[] bytes = new byte[1024 * 1024];
    //用于返回字节数组大小
    private int receiveNum;
    //客户端Socket
    public Socket socket;
    private bool IsConnect=false;

    void Awake()
    {
        instance = this;    
    }
    void Update()
    {
        if(receiveMgsQueue .Count >0)
        {
            print(receiveMgsQueue.Dequeue());
        }
    }
    //连接服务器
    public void Connect(string ip,int port)
    {//如果是非链接状态,直接返回
        if (IsConnect )
            return;
        if(socket==null)
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //连接服务端
        IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip),port);
        try
        {
            socket.Connect(ipPoint);
            IsConnect  = true;
            //使用线程池节约性能
            ThreadPool.QueueUserWorkItem(SendMsg);
            ThreadPool.QueueUserWorkItem(ReceiveMsg);
        }
        catch (SocketException e)
        {
            if (e.ErrorCode == 10061)
                print("服务器拒绝连接");
            else
                print("连接失败" + e.ErrorCode + e.Message);
        }
    
    }
    //发送消息
    public void Send(string info)
    {
        sendMgsQueue.Enqueue(info);
    }
    public void SendMsg(object obj)
    {
        if(sendMgsQueue .Count >0)
        {
            socket.Send(Encoding.UTF8.GetBytes(sendMgsQueue.Dequeue()));
        }
    }
    //不停的接收消息
    public void ReceiveMsg(object obj)
    {
        while (IsConnect)
        {
            if (socket.Available > 0)
            {
                receiveNum = socket.Receive(bytes);
                //解析字符数组成字符串,放入公共容器中
                receiveMgsQueue.Enqueue(Encoding.UTF8.GetString(bytes, 0, receiveNum));
            }
        }
 
    }
    public void Close()
    {
        if(socket !=null)
        {
            IsConnect  = false;
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
    }
    private void OnDestroy()
    {
        Close();
    }
}

主函数入口

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Main : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        if(NetMgr .Instance ==null)
        {
            GameObject obj = new GameObject("Net");
            obj.AddComponent<NetMgr>();
        }
        NetMgr.Instance.Connect("127.0.0.1", 8080);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

客户端向服务器发消息

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Lesson7 : MonoBehaviour
{
    public Button btu;
    public InputField input;
    void Start()
    {
        btu.onClick.AddListener(() =>
      {
          if (input.text != "")
          {
              NetMgr.Instance.Send(input.text);
          }
      }
        );
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
相关推荐
せいしゅん青春之我28 分钟前
【JavaEE初阶】网络原理——TCP报文结构、确认应答机制
网络·笔记·网络协议·tcp/ip·java-ee
Python私教1 小时前
Unity 游戏开发「工业化级」学习路线 2025 版
学习·unity·游戏引擎
☆璇2 小时前
【Linux】数据链路层
linux·服务器·网络
电鱼智能的电小鱼3 小时前
基于电鱼 ARM 工控机的AI视频智能分析方案:让传统监控变得更聪明
网络·arm开发·人工智能·嵌入式硬件·算法·音视频
2501_915909064 小时前
网络调试工具推荐 Fiddler抓包工具使用教程与代理设置详解(HTTP/HTTPS配置与实战技巧)
网络·http·ios·小程序·fiddler·uni-app·webview
芙蓉王真的好15 小时前
初阶吃透:HTTP 请求行的格式(Method + URL + Version)详解
网络·网络协议·http
小武~5 小时前
嵌入式网络编程深度探索:无线网络驱动开发实战指南
网络·驱动开发
于小汐在咯6 小时前
【Unity每日一记】Unity物理引擎:刚体与碰撞体详解
unity·游戏引擎
我叫汪枫6 小时前
《HTTPS 的灵魂:加密、认证与数字证书》
网络协议·http·https
Rysxt_7 小时前
MQTT 与 WebSocket 对比教程:物联网与实时通信协议选择指南
物联网·websocket·网络协议