你想在unity WebGL里面使用TCP通信吗,那么你可以用一用webSocket。当然,桌面端也可以使用webSocket,这样Unity多平台发布的时候,业务层的通信代码可以使用一套,而不是桌面用socket,网页用http…
一、什么是webSocket?
顾名思义,它就是web版的socket?那什么是socket呢?…
二、Unity中webSocket相关的包有哪些?
endel/NativeWebSocket
项目链接
三、Unity客户端的实现
- 联网演示
- 绑定脚本
- 代码清单代码来自NativeWebSocket官网demo,略作修改
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.UI;usingNativeWebSocket;publicclassConnection:MonoBehaviour{WebSocket websocket;publicText textLog;// Start is called before the first frame updateasyncvoidStart(){
websocket =newWebSocket("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 stringvar 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.3sInvokeRepeating("SendWebSocketMessage",0.0f,0.3f);// waiting for messagesawait websocket.Connect();}voidUpdate(){#if !UNITY_WEBGL || UNITY_EDITOR
websocket.DispatchMessageQueue();#endif}asyncvoidSendWebSocketMessage(){if(websocket.State == WebSocketState.Open){// Sending bytesawait websocket.Send(newbyte[]{10,20,30});// Sending plain textawait websocket.SendText("plain text message");}}privateasyncvoidOnApplicationQuit(){await websocket.Close();}}
四、服务端的实现(C# WinForm)
1、服务器端用到的包
github链接
2、主要代码
代码来自官网Demo,略有修改
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingFleck;namespaceWinFormsApp1{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}privatevoidbutton1_Click(object sender,EventArgs e){var server =newWebSocketServer("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,现在可以统一了。
版权归原作者 dzj2021 所有, 如有侵权,请联系我们删除。