- Unity版本:2018.4.17
- BestHTTP版本:1.11.0 (下载地址)
BestHTTP是Unity商店中比较流行的网络插件,兼容几乎所有的移动和独立平台。除了基础的HTTP功能,还支持WebSocket、SocketIO等常用特性,可以满足一般游戏项目的所有网络需求。
安装
下载Best HTTP v1.11.0.unitypackage
后,Unity编辑器中右键"Import Package" -> "Custom Package"
导入,然后在需要的代码中引入命名空间,就可以使用了。
using BestHTTP;
使用HTTP
进行HTTP请求非常简单,把目标Url作为构造参数创建 HTTPRequest
类实例,并调用Send
即可,推荐使用下面这种回调写法,简洁而清晰。
string str = "http://xxx.xxx.xxx.xxx?xx";
new HTTPRequest(new Uri(str), (req, response) => {
string text = response.DataAsText; // 服务器回复
Debug.Log("response data is " +text);
}).Send();
使用WebSocket
创建WebSocket对象,并为该对象设置好Socket打开、消息接收、错误处理等各种回调。
需要注意的是,WebSocket消息的接收有两个方法:OnMessage和OnBinary,分别代表字符串和字节,具体使用哪个,需根据各自客户端和服务器的协议而定。
public class WebSocketTest
{
string address = "wss://echo.websocket.org";
WebSocket webSocket;
public void Init()
{
if (webSocket == null)
{
webSocket = new WebSocket(new Uri(address));
#if !UNITY_WEBGL
webSocket.StartPingThread = true;
#endif
// Subscribe to the WS events
webSocket.OnOpen += OnOpen;
webSocket.OnMessage += OnMessageRecv;
webSocket.OnBinary += OnBinaryRecv;
webSocket.OnClosed += OnClosed;
webSocket.OnError += OnError;
// Start connecting to the server
webSocket.Open();
}
}
public void Destroy()
{
if (webSocket != null)
{
webSocket.Close();
webSocket = null;
}
}
void OnOpen(WebSocket ws)
{
Debug.Log("OnOpen: ");
webSocket.Send("123");
}
void OnMessageRecv(WebSocket ws, string message)
{
Debug.LogFormat("OnMessageRecv: msg={0}", message);
}
void OnBinaryRecv(WebSocket ws, byte[] data)
{
Debug.LogFormat("OnBinaryRecv: len={0}", data.Length);
}
void OnClosed(WebSocket ws, UInt16 code, string message)
{
Debug.LogFormat("OnClosed: code={0}, msg={1}", code, message);
webSocket = null;
}
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.LogFormat("OnError: error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
webSocket = null;
}
}