之前在WebGL平台和服务端交互的时候使用的是UnityWebRequest,通过WebAPI的方式进行交互,后来发现可以用WebSocket交互后就果断换了WebSocket。
一、Unity3D客户端
我在Unity端使用的是NativeWebSocket
NativeWebSocket下载地址
直接导入Unity即可,
下面是适配的代码,直接挂载在GameObject。
文章来源地址https://www.toymoban.com/news/detail-680320.html
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using NativeWebSocket;
using LitJson;
public class Connection : MonoBehaviour
{
WebSocket websocket;
public Text textLog;
async void Start()
{
websocket = new WebSocket("ws://127.0.0.1:7181");
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.Default.GetString(bytes);
textLog.text = $"消息内容:{message} ";
Debug.Log("OnMessage! " + message);
//SocketData Sdata= JsonMapper.ToObject<SocketData>(message);
var Sdata=JsonMapper.ToObject< Dictionary<string, string>>(message);
Debug.Log(Sdata["data"]);
string b = Sdata["data"];
byte[] bs= Convert.FromBase64String(b);
var m = System.Text.Encoding.Default.GetString(bs);
Debug.Log(m);
};
// Keep sending messages at every 0.3s
// InvokeRepeating("SendWebSocketMessage", 0.0f, 2f);
// 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();
}
}
二、服务端
运行后可与客户端交互
下载地址
文章来源:https://www.toymoban.com/news/detail-680320.html
到了这里,关于Unity3D WebGL平台使用WebSocket通信的方法和示例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!