最近工作中需要和服务器交互、传输数据,服务器端用的就是WebSocket,在此之前也是在网上翻翻找找,还是BestHttp这个插件好用、在此记录下,当做记笔记了、代码部分也参考了前辈的写法,也算是前人栽树后人乘凉了。
一、导入插件
点击上面链接下载、解压后导入unity中
二、相关脚本代码
- 这里我创建了DataMagnage脚本
- 引入头文件(我这里是直接粘贴我项目中的代码、引入了其他的头文件,不需要的头文件呈灰色删掉就好)
using System; using System.Text; using UnityEngine; using UnityEngine.UI; using BestHTTP.WebSocket; using System.Collections.Generic; using Newtonsoft.Json.Linq; using System.Collections; using System.Threading;
-
相关连接、初始化以及接收数据、关闭、抛出异常代码(这里URL地址建议在外部使用配置文件获取,后面会写unity读取XML文件方法)
/// <summary> /// --------------------这是需要连接的URL地址 /// </summary> public string url = "ws://localhost:8080//websocket/"; private WebSocket webSocket; private void Init() { webSocket = new WebSocket(new Uri(url)); webSocket.OnOpen += OnOpen; webSocket.OnMessage += OnMessageReceived; webSocket.OnError += OnError; webSocket.OnClosed += OnClosed; } private void AntiInit() { webSocket.OnOpen = null; webSocket.OnMessage = null; webSocket.OnError = null; webSocket.OnClosed = null; webSocket = null; } public void Connect() { webSocket.Open(); print("发送连接"); } private byte[] getBytes(string message) { byte[] buffer = Encoding.Default.GetBytes(message); return buffer; } public void Send(string str) { webSocket.Send(str); } public void Close() { webSocket.Close(); } void OnOpen(WebSocket ws) { Debug.Log("连接成功"); } /// <summary> /// 接收信息 /// </summary> /// <param name="ws"></param> /// <param name="msg">接收内容</param> void OnMessageReceived(WebSocket ws,string msg) { Debug.Log(msg); SetLog(msg); } /// <summary> /// 关闭连接 /// </summary> void OnClosed(WebSocket ws, UInt16 code, string message) { Debug.Log(message); setConsoleMsg(message); antiInit(); init(); } private void OnDestroy() { if (webSocket != null && webSocket.IsOpen) { webSocket.Close(); antiInit(); } } /// <summary> /// Called when an error occured on client side /// </summary> void OnError(WebSocket ws, Exception ex) { string errorMsg = string.Empty; #if !UNITY_WEBGL || UNITY_EDITOR if (ws.InternalRequest.Response != null) errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message); #endif Debug.Log(errorMsg); setConsoleMsg(errorMsg); antiInit(); init(); }
-
然后就是调用方法,如果直接在进入场景后调用就把init();Connect();两个方法写在Start()里面就行了。
三、总结
我是直接在我项目中将相关代码粘出来的、就不再写Demo了。
注意:
建议把该脚本和BestHTTP文件夹放在一起,不然可能会报错……