Unity中的简易TCP服务器/客户端

在本文中,我将向你介绍一个在Unity中实现的简单TCP服务器脚本,和一个简单的客户端脚本.

脚本 MyTcpServer 允许Unity应用创建一个TCP服务器,监听客户端的连接、异步处理客户端消息,并通过事件与Unity应用中的其他模块进行通信。

MyTcpServer 类是使用 C# 的 TcpListener 实现的自定义 TCP 服务器,该服务器监听指定端口的传入 TCP 连接,并以异步、非阻塞的方式处理与客户端的通信.

AcceptClientsAsync 方法是一个异步方法,使用 TcpListener.AcceptTcpClientAsync() 来接受客户端的连接。每当一个新客户端连接时,服务器会将其添加到 connectedClients 列表中,并为该客户端创建一个新的任务 (Task.Run()) 来处理客户端的消息。

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using System.IO;
using System.Collections.Generic;public class MyTcpServer
{private static MyTcpServer instance;private TcpListener tcpListener;private CancellationTokenSource cts = new CancellationTokenSource();private List<TcpClient> connectedClients = new List<TcpClient>(); // 管理客户端连接public static bool isOnce = false;public static event Action<string> sendEvent;public static MyTcpServer Instance{get{if (instance == null){instance = new MyTcpServer();}return instance;}}public void StartServer(){try{var p = Path.Combine(Application.streamingAssetsPath, "MyPort.txt");if (!File.Exists(p)) return;var port = File.ReadAllText(p, Encoding.UTF8);Debug.Log($"Starting server on port {port}");tcpListener = new TcpListener(IPAddress.Any, int.Parse(port));tcpListener.Start();isOnce = true;Task.Run(() => AcceptClientsAsync(cts.Token));}catch (Exception ex){Debug.LogError($"Error starting server: {ex.Message}");}}private async Task AcceptClientsAsync(CancellationToken token){while (!token.IsCancellationRequested){try{TcpClient client = await tcpListener.AcceptTcpClientAsync();Debug.Log($"Client connected: {client.Client.RemoteEndPoint}");connectedClients.Add(client);_ = Task.Run(() => HandleClientAsync(client, token));}catch (Exception ex){Debug.LogError($"Error accepting client: {ex.Message}");}}}private async Task HandleClientAsync(TcpClient client, CancellationToken token){using (client){NetworkStream stream = client.GetStream();byte[] buffer = new byte[4096];while (!token.IsCancellationRequested){try{int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, token);if (bytesRead == 0) break;string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);Debug.Log($"Received: {message}");sendEvent?.Invoke(message);}catch (Exception ex){Debug.LogError($"Error reading from client: {ex.Message}");break;}await Task.Delay(10, token);}}// Cleanup on client disconnectconnectedClients.Remove(client);}public void StopServer(){if (cts != null){cts.Cancel();if (tcpListener != null){tcpListener.Stop();tcpListener = null;}cts.Dispose();cts = null;}// Ensure that all connected clients are closed properlyforeach (var client in connectedClients){client.Close();}connectedClients.Clear();}
}

MyClient 类是一个简单的客户端实现,能够与 TCP 服务器进行通信。它提供了连接服务器、发送命令以及关闭连接等基本功能。

using System.Collections;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;public class MyClient
{private TcpClient client;private NetworkStream stream;private static MyClient _ins; // 单例实例private static bool connected = false;public static MyClient ins{get{if (_ins == null){_ins = new MyClient();}return _ins;}}// 私有构造函数,防止外部实例化private MyClient(){}public void Init(){if (!connected){connected = true;var path = Path.Combine(Application.streamingAssetsPath, "IpFile.txt");var p = Path.Combine(Application.streamingAssetsPath, "MyPort.txt");if (!File.Exists(p) || !File.Exists(path)) return;Debug.Log($"Reading IP configuration from: {path}");Debug.Log($"Reading port from: {p}");var ipAddress = File.ReadAllText(path, Encoding.UTF8);var port = File.ReadAllText(p, Encoding.UTF8);Debug.Log(ipAddress);Debug.Log(port);ConnectToServer(ipAddress, int.Parse(port));}}private async void ConnectToServer(string ip, int port){int maxRetryAttempts = 5; // 最大重试次数int retryDelayMilliseconds = 1500; // 重试间隔,单位为毫秒for (int attempt = 1; attempt <= maxRetryAttempts; attempt++){try{client = new TcpClient();await client.ConnectAsync(ip, port); // 异步连接服务器stream = client.GetStream();Debug.Log("Connected to server.");return; // 成功连接则退出方法}catch (SocketException e){Debug.LogError($"Attempt {attempt} failed to connect: {e.Message}");if (attempt < maxRetryAttempts){Debug.Log($"Retrying in {retryDelayMilliseconds / 1000} seconds...");await Task.Delay(retryDelayMilliseconds); // 等待重试}else{Debug.LogError("Max retry attempts reached. Unable to connect to server.");}}}}public async Task SendCommand(string command){if (stream != null && client.Connected){try{byte[] data = Encoding.UTF8.GetBytes(command);await stream.WriteAsync(data, 0, data.Length); // 发送数据到服务器Debug.Log($"Command sent: {command}");}catch (SocketException e){Debug.LogError($"Error sending command: {e.Message}");}}else{Debug.LogWarning("Not connected to server.");}}public void CloseConnection(){if (stream != null){stream.Close();stream = null;}if (client != null){client.Close();client = null;}Debug.Log("Connection closed.");}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/887509.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

架构-微服务-服务网关

文章目录 前言一、网关介绍1. 什么是API网关2. 核心功能特性3. 解决方案 二、Gateway简介三、Gateway快速入门1. 基础版2. 增强版3. 简写版 四、Gateway核心架构1. 基本概念2. 执行流程 五、Gateway断言1. 内置路由断言工厂2. 自定义路由断言工厂 六、过滤器1. 基本概念2. 局部…

idea怎么打开两个窗口,运行两个项目

今天在开发项目的时候&#xff0c;前端希望运行一下以前的项目&#xff0c;于是就需要开两个 idea 窗口&#xff0c;运行两个项目 这里记录一下如何设置&#xff1a;首先依次点击&#xff1a; File -> Settings -> Appearance & Behavior ->System Settings 看到如…

零碎04 MybatisPlus自定义模版生成代码

目录 背景 动手开干 需要的依赖包&#xff0c;需要注意mybatis-plus-generator的3.5版本是没有兼容历史版本的。 定义一个CodeGenerator类&#xff0c;负责生成代码和配置属性 Entity模版 背景 MybatisPlus代码生成使用默认的velocity模版解决不了定制化的需求&#xff0…

CentOS8.5.2111(7)完整的Apache综合实验

一、实验目标 1.掌握Linux系统中Apache服务器的安装与配置&#xff1b; 2.掌握个人主页、虚拟目录、基于用户和主机的访问控制及虚拟主机的实现方法。 二、实验要求 练习使用linux系统下WEB服务器的配置方法。 三、实验背景 重庆工程学院为筹备“重庆工程大学”特申请了c…

Cocos编辑器

1、下载 下载地址&#xff1a;https://www.cocos.com/creator-download 2、编辑器界面介绍 官方链接&#xff1a;https://docs.cocos.com/creator/3.8/manual/zh/editor/ 3、项目结构 官方链接&#xff1a;https://docs.cocos.com/creator/3.8/manual/zh/getting-started/…

Easyui 实现订单拆分开票功能

Easyui 实现订单拆分开票功能 需求 1、实现一个订单开具多分发票功能&#xff1b; 2、支持拆行&#xff1b; 3、支持拆数量&#xff1b; 流程设计 1、操作页面展示订订单头信息&#xff0c;订单明细信息 2、点击新增发票按钮弹出一个弹出框用于创建一张拆分发票&#xff0c;弹…

Linux中的“块”是什么

在Linux系统中&#xff0c;块&#xff08;block&#xff09;是文件系统存储数据的基本单位&#xff0c;以下是关于Linux中块的概念和使用场景的详细解释&#xff1a; 一、块的概念 定义&#xff1a;块是多个连续性的扇区&#xff08;sector&#xff09;组成&#xff0c;扇区是…

解决 java -jar 报错:xxx.jar 中没有主清单属性

问题复现 在使用 java -jar xxx.jar 命令运行 Java 应用程序时&#xff0c;遇到了以下错误&#xff1a; xxx.jar 中没有主清单属性这个错误表示 JAR 文件缺少必要的启动信息&#xff0c;Java 虚拟机无法找到应用程序的入口点。本文将介绍该错误的原因以及如何通过修改 pom.xm…

推荐一款龙迅HDMI2.0转LVDS芯片 LT6211UX LT6211UXC

龙迅的HDMI2.0转LVDS芯片LT6211UX和LT6211UXC是两款高性能的转换器芯片&#xff0c;它们在功能和应用上有所差异&#xff0c;同时也存在一些共同点。以下是对这两款芯片的详细比较和分析&#xff1a; 一、LT6211UX 主要特性&#xff1a; HDMI2.0至LVDS和MIPI转换器。HDMI2.0输…

flink学习(7)——window

概述 窗口的长度(大小): 决定了要计算最近多长时间的数据 窗口的间隔: 决定了每隔多久计算一次 举例&#xff1a;每隔10min,计算最近24h的热搜词&#xff0c;24小时是长度&#xff0c;每隔10分钟是间隔。 窗口的分类 1、根据window前是否调用keyBy分为键控窗口和非键控窗口…

C语言解析命令行参数

原文地址&#xff1a;C语言解析命令行参数 – 无敌牛 欢迎参观我的个人博客&#xff1a;无敌牛 – 技术/著作/典籍/分享等 C语言有一个 getopt 函数&#xff0c;可以对命令行进行解析&#xff0c;下面给出一个示例&#xff0c;用的时候可以直接copy过去修改&#xff0c;很方便…

深入解析 ArrayList 源码:从动态扩容到高效存取的秘密

全文目录&#xff1a; 开篇语目录&#x1f31f; 前言&#x1f9e9; ArrayList 概述&#x1f3d7;️ ArrayList 的底层实现&#x1f4d0; 构造函数详解&#x1f3d7;️ 数组的动态扩容机制 ⚙️ 核心方法源码解析➕ add() 方法的实现➖ remove() 方法的实现&#x1f50d; get() …

Amazon AWS公司介绍

Amazon Web Services&#xff08;AWS&#xff09;是亚马逊公司&#xff08;Amazon&#xff09;的子公司&#xff0c;提供广泛的云计算服务&#xff0c;包括弹性计算、存储解决方案、数据库服务、机器学习、物联网&#xff08;IoT&#xff09;和企业应用等。以下是AWS的一些关键…

精密工装夹具加工:打造高精度产品

在现代制造业中&#xff0c;精密工装夹具加工扮演着关键角色&#xff0c;是打造高精度产品不可缺少的环节。 精密工装夹具的设计与制造&#xff0c;首先依赖于对加工工艺的深入理解与精准把握。工程师们需要根据待加工产品的形状、尺寸、精度要求以及加工设备的特性&#xff0c…

使用client-go在命令空间test里面对pod进行操作

目录 一、获取使用restApi调用的token信息 二、client-go操作pod示例 1、获取到客户端 2、创建pod 3、获取test命令空间的所有pod 4、获取某个具体pod的详细信息 5、更新pod 6、删除pod 三、总结 官方参考地址&#xff1a;https://kubernetes.io/docs/reference/kuber…

C++ 优先算法 —— 无重复字符的最长子串(滑动窗口)

目录 题目&#xff1a; 无重复字符的最长子串 1. 题目解析 2. 算法原理 Ⅰ. 暴力枚举 Ⅱ. 滑动窗口&#xff08;同向双指针&#xff09; 3. 代码实现 Ⅰ. 暴力枚举 Ⅱ. 滑动窗口 题目&#xff1a; 无重复字符的最长子串 1. 题目解析 题目截图&#xff1a; 此题所说的…

huggingface使用

import warnings warnings.filterwarnings("ignore") from transformers import pipeline#用人家设计好的流程完成一些简单的任务 classifier pipeline("sentiment-analysis") classifier( [ "Ive been waiting for a HuggingFace cours…

qt 读写文本、xml文件

写txt文件 QString fileName ui->lineEdit->text(); QString fileContent ui->textEdit->toPlainText(); qDebug()<<"test:"<<fileContent; QFile file(fileName); if(!file.open(QFile::WriteOnly|QFile::Text)) { …

第六届机器人、智能控制与人工智能国际(RICAI 2024)

会议信息 会议时间与地点&#xff1a;2024年12月6-8日&#xff0c;中国南京 会议官网&#xff1a;www.ic-ricai.org &#xff08;点击了解大会参会等详细内容&#xff09; 会议简介 第六届机器人、智能控制与人工智能国际学术会议&#xff08;RICAI 2024&#xff09;将于20…

【设计模式】创建型模式之单例模式(饿汉式 懒汉式 Golang实现)

定义 一个类只允许创建一个对象或实例&#xff0c;而且自行实例化并向整个系统提供该实例&#xff0c;这个类就是一个单例类&#xff0c;它提供全局访问的方法。这种设计模式叫单例设计模式&#xff0c;简称单例模式。 单例模式的要点&#xff1a; 某个类只能有一个实例必须…