Unity使用webSocket与服务器通信(一)搭建一个简单地服务器和客户端
创始人
2025-01-20 10:04:05
0

你想在unity WebGL里面使用TCP通信吗,那么你可以用一用webSocket。当然,桌面端也可以使用webSocket,这样Unity多平台发布的时候,业务层的通信代码可以使用一套,而不是桌面用socket,网页用http…

一、什么是webSocket?

顾名思义,它就是web版的socket?那什么是socket呢?…

二、Unity中webSocket相关的包有哪些?

endel/NativeWebSocket
项目链接

在这里插入图片描述

在这里插入图片描述

三、Unity客户端的实现

  • 联网演示
    请添加图片描述

  • 绑定脚本
    在这里插入图片描述

  • 代码清单
    代码来自NativeWebSocket官网demo,略作修改

using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using NativeWebSocket;  public class Connection : MonoBehaviour {     WebSocket websocket;      public Text textLog;      // Start is called before the first frame update     async void Start()     {         websocket = new WebSocket("ws://192.168.0.146:8081");          websocket.OnOpen += () =>         {             Debug.Log("Connection open!");             textLog.text = $"Connection open! {Time.realtimeSinceStartup} \n {textLog.text}";         };          websocket.OnError += (e) =>         {             Debug.Log("Error! " + e);             textLog.text = $"Error:{e} {Time.realtimeSinceStartup} \n {textLog.text}";         };          websocket.OnClose += (e) =>         {             Debug.Log("Connection closed!");             textLog.text = $"Connection closed! {Time.realtimeSinceStartup} \n {textLog.text}";         };          websocket.OnMessage += (bytes) =>         {             Debug.Log("OnMessage!");             textLog.text = $"OnMessage! {Time.realtimeSinceStartup} \n {textLog.text}";             Debug.Log(bytes);              // getting the message as a string             var message = System.Text.Encoding.UTF8.GetString(bytes);             textLog.text = $"消息内容:{message} {Time.realtimeSinceStartup} \n {textLog.text}";             //Debug.Log("OnMessage! " + message);         };          // Keep sending messages at every 0.3s         InvokeRepeating("SendWebSocketMessage", 0.0f, 0.3f);          // waiting for messages         await websocket.Connect();     }      void Update()     { #if !UNITY_WEBGL || UNITY_EDITOR         websocket.DispatchMessageQueue(); #endif     }      async void SendWebSocketMessage()     {         if (websocket.State == WebSocketState.Open)         {             // Sending bytes             await websocket.Send(new byte[] { 10, 20, 30 });              // Sending plain text             await websocket.SendText("plain text message");         }     }      private async void OnApplicationQuit()     {         await websocket.Close();     }  } 

四、服务端的实现(C# WinForm)

在这里插入图片描述
请添加图片描述

1、服务器端用到的包

在这里插入图片描述
在这里插入图片描述

github链接

2、主要代码

代码来自官网Demo,略有修改

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Fleck;  namespace WinFormsApp1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             var server = new WebSocketServer("ws://192.168.0.146:8081");  //ws://localhost:8081    ws://127.0.0.0:8181             server.Start(socket =>             {                 socket.OnOpen = () =>                 {                     Debug.WriteLine($"有新用户连入:{socket.ConnectionInfo.ClientIpAddress}");                 };                 socket.OnClose = () =>                 {                     Debug.WriteLine($"用户断开连接:{socket.ConnectionInfo.ClientIpAddress}");                 };                 socket.OnMessage = message =>                 {                     socket.Send($"服务器收到消息 : {DateTime.Now.ToString()}");                     Debug.WriteLine($"收到一条消息,来自:{socket.ConnectionInfo.ClientIpAddress}");                 };             });              Debug.WriteLine("服务器已经启动!");         }     } } 

五、客户端的WebGL和Win 桌面测试

桌面和webGL都没问题、这样,可以一套代码打天下。
以前用socket在桌面(包括一体头盔),在web端只能用http,现在可以统一了。

相关内容

热门资讯

突发!hhpoker透视脚本下... 突发!hhpoker透视脚本下载,德普之星透视辅助软件下载,一贯是真的有挂(有挂教学)德普之星透视辅...
代打辅助挂!wpk俱乐部是做什... 代打辅助挂!wpk俱乐部是做什么的,德普软件,一直存在有挂(有挂神器)德普软件辅助器是一种具有地方特...
2026版教学!pokemmo... 2026版教学!pokemmo辅助器手机版下载,德普之星透视辅助,切实是有挂(有挂详细)1、该软件可...
教程辅助挂!wepoker插件... 教程辅助挂!wepoker插件辅助,德普之星私人局辅助器,果然真的有挂(今日头条)1、玩家可以在德普...
一直以来!cloudpoker... 一直以来!cloudpoker外挂,德扑之星透视软件免费入口官网,本来是真的有挂(竟然有挂)1、德扑...
做出回应!wepoker游戏安... 做出回应!wepoker游戏安装教程,智星菠萝透视,竟然存在有挂(的确有挂)亲,关键说明,智星菠萝透...
今日!wepoker免费辅助器... 今日!wepoker免费辅助器,德普之星app安卓版破解版,确实是有挂(有挂细节)1、很好的工具软件...
总结辅助挂!德普之星辅助工具如... 总结辅助挂!德普之星辅助工具如何打开,德扑之星怎么开辅助,一直真的有挂(证实有挂)1、下载好德普之星...
黑科技插件!hhpoker透视... 黑科技插件!hhpoker透视方法,德扑圈有透视吗,真是存在有挂(有挂总结)1、下载好德扑圈有透视吗...
第三方插件!wejoker辅助... 第三方插件!wejoker辅助软件,智星菠萝辅助,一直是真的有挂(有挂解密)1、全新机制【智星菠萝辅...