欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 实现客户端的网络不影响主线程且随时与服务器通信

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

2025/3/15 19:26:50 来源:https://blog.csdn.net/2301_79609157/article/details/146216934  浏览:    关键词:实现客户端的网络不影响主线程且随时与服务器通信
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(){}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词