🏆 个人愚见,没事写写笔记
🏆《博客内容》:Unity3D开发内容
🏆🎉欢迎 👍点赞✍评论⭐收藏
🔎目标:服务器和客户端可以实时的传输信息
☀️实现目标:
使用的websocket插件:NativeWebSocket
客户端代码:
csusing NativeWebSocket; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR; using WebSocketState = NativeWebSocket.WebSocketState; public class WebSocketClient : MonoBehaviour { private WebSocket _webSocket; public string webSocketServerURL = "ws://10.2.17.23:28080"; private void Awake() { _webSocket = new WebSocket(webSocketServerURL); } private void Start() { _webSocket.OnOpen += _OnOpen;//连接成功时 _webSocket.OnClose += _OnClose;//连接关闭 _webSocket.OnError += _OnError;//连接出错 _webSocket.OnMessage += _OnMessage;//从服务器发来的消息 OnConnectServer();//开始连接服务器 } private async void OnApplicationQuit() { await _webSocket.Close(); } private void Update() { #if !UNITY_WEBGL || UNITY_EDITOR _webSocket.DispatchMessageQueue(); #endif if (Input.GetKeyDown(KeyCode.S)) { SendMessageToServer(); } } public async void OnConnectServer() { await _webSocket.Connect(); } public async void SendMessageToServer() { if (_webSocket.State == WebSocketState.Open) { await _webSocket.Send(new byte[] { 10, 20, 30 });//发送一条字节数据 await _webSocket.SendText("发送一条string数据"); } } #region WebSocket 回调事件 private void _OnOpen() { Debug.Log("连接成功"); } private void _OnClose(WebSocketCloseCode closeCode) { Debug.Log("连接关闭"); } private void _OnError(string errorMsg) { Debug.LogError("出错原因:" + errorMsg); } private void _OnMessage(byte[] dataBytes) { var message = System.Text.Encoding.UTF8.GetString(dataBytes); Debug.Log("接收到的消息: (" + dataBytes.Length + " bytes) " + message); } #endregion }