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

ops/2025/3/13 5:28:00/
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;//客户端Socketpublic 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("服务器拒绝连接");elseprint("连接失败" + 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 updatevoid 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 framevoid 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 framevoid Update(){}
}


http://www.ppmy.cn/ops/165338.html

相关文章

C#枚举(Enum)详解

在 C# 中&#xff0c;‌枚举&#xff08;Enum&#xff09;‌ 是一种值类型&#xff0c;用于定义一组命名的常量值&#xff0c;提高代码的可读性和可维护性。以下是枚举的核心概念、用法和最佳实践&#xff1a; ‌1. 枚举的核心特性‌ 类型安全‌&#xff1a;避免使用魔法数字&…

win32汇编环境,对 WM_MOUSEMOVE 消息的理解

;运行效果 ;win32汇编环境,对 WM_MOUSEMOVE 消息的理解 ;理解在 WM_MOUSEMOVE 消息发生时&#xff0c;同时来的wParam和lParam值的含义&#xff0c;并取出各自的值进行运用。从这例子也可以更好的理解windows的消息机制. ;WM_MOUSEMOVE消息就是当鼠标移动时&#xff0c;发送给窗…

解决电脑问题(4)——主机问题

电脑主机出现问题的原因较为复杂&#xff0c;以下是一些常见问题及解决方法&#xff1a; 主机无法开机 检查电源连接&#xff1a;首先确保主机电源线插头牢固插入插座&#xff0c;且插座通电正常&#xff0c;可以尝试将其他电器设备插入该插座来验证。同时检查主机电源开关是否…

记录一下Django的密码重置(忘记密码)

一. Django默认的密码重置 1.路由 # url.pyfrom django.contrib.auth import views as auth_viewsurlpatterns [# 密码重置path(password_reset/, auth_views.PasswordResetView.as_view(), namepassword_reset),# 用户输入邮箱后&#xff0c;跳转到此页面path(password_res…

深入了解住宅IP:跨境电商中的重要工具

在全球化电商竞争白热化的今天&#xff0c;"账号无故被封"、"视频播放量归零"等问题如同达摩克利斯之剑悬在运营者头顶。这些看似无解的困境背后&#xff0c;往往隐藏着一个关键变量——IP质量。本文将深入剖析住宅IP这一数字时代的"身份通行证"…

【Linux docker】关于docker启动出错的解决方法。

无论遇到什么docker启动不了的问题 就是 查看docker状态sytemctl status docker查看docker日志sudo journalctl -u docker.service查看docker三个配置文件&#xff08;可能是配置的时候格式错误&#xff09;&#xff1a;/etc/docker/daemon.json&#xff08;如果存在&#xf…

SpringMVC 6+ 依赖的 servlet 版本问题

在 Spring MVC 6.0.14 版本中&#xff0c;Spring 不再依赖 Java EE&#xff08;Jakarta EE 8 及以下&#xff09;&#xff0c;而是完全迁移到 Jakarta EE 9&#xff0c;即所有 javax.servlet 相关包都被替换成了 jakarta.servlet &#x1f50d; Spring MVC 6.0.14 依赖的 Servl…

Spring 面向切面编程 XML 配置实现

Spring 支持AOP &#xff0c;并且可以通过XML配置来实现。 <beans xmlns"http://www.springframework.org/schema/beans"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xmlns:aop"http://www.springframework.org/schema/aop"xmlns:…