当前位置: 首页 > article >正文

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

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();
    }
}

主函数入口

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()
    {
        
    }
}

客户端向服务器发消息

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()
    {
        
    }
}


http://www.kler.cn/a/582441.html

相关文章:

  • html-表格标签
  • 蓝桥杯省赛真题C++B组-裁纸刀2022
  • 计算机视觉实战|NeRF 实战教程:基于 nerf_recon_dataset 的三维重建
  • MySQL库和表的操作详解:从创建库到表的管理全面指南
  • 45.HarmonyOS NEXT Layout布局组件系统详解(十二):高级应用案例与性能优化
  • 无标记点动作捕捉系统,无需穿戴设备,摄像头智能采集人体运动姿态
  • Webpack 优化深度解析:从构建性能到输出优化的全面指南
  • TDengine SQL 函数
  • JVM和运行时数据区
  • 国产化信创操作系统的电脑,能运行windows程序吗
  • 关于回归中R2指标的理解
  • docker搭建elk
  • 【学写LibreCAD】 4.1 RS_Undoable文件
  • 【Linux内核系列】:文件系统
  • 一文说清docker及docker compose的应用和部署
  • UI显示不出来问题(有的能显示出来一个方法,有的数据显示不出来另一个方法),多次尝试无果
  • CSPM-3级国标认证,项目管理如何成为组织变革的核心引擎?
  • 裂变营销策略在“开源链动2+1模式AI智能名片S2B2C商城小程序”中的应用探索
  • JavaScript性能优化实战:让你的Web应用飞起来
  • AI+API引爆数据分析:BI已成过去?