117 lines
3.0 KiB
C#
117 lines
3.0 KiB
C#
using System;
|
|
using BestHTTP.WebSocket;
|
|
using UnityEngine;
|
|
|
|
//[System.Serializable]
|
|
public class WebSocketT /*: MonoBehaviour*/
|
|
{
|
|
//string address = "ws://127.0.0.1:8081/websocket";
|
|
WebSocket webSocket;
|
|
|
|
public void Init(string address)
|
|
{
|
|
if (webSocket == null)
|
|
{
|
|
webSocket = new WebSocket(new Uri(address));
|
|
|
|
#if !UNITY_WEBGL
|
|
webSocket.StartPingThread = true;
|
|
#endif
|
|
|
|
//订阅WS事件
|
|
webSocket.OnOpen += OnOpen;
|
|
webSocket.OnMessage += OnMessageRecv;
|
|
webSocket.OnBinary += OnBinaryRecv;
|
|
webSocket.OnClosed += OnClosed;
|
|
webSocket.OnError += OnError;
|
|
|
|
//开始连接到服务器
|
|
webSocket.Open();
|
|
}
|
|
}
|
|
|
|
private void OnError(WebSocket ws, string reason)
|
|
{
|
|
string errorMsg = string.Empty;
|
|
#if !UNITY_WEBGL || UNITY_EDITOR
|
|
if (ws.InternalRequest.Response != null)
|
|
{
|
|
errorMsg = string.Format("服务器的状态码: {0} 消息: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
|
|
}
|
|
#endif
|
|
Debug.LogFormat("OnError:错误发生: {0}", errorMsg);
|
|
webSocket = null;
|
|
}
|
|
|
|
public void Destroy()
|
|
{
|
|
if (webSocket != null)
|
|
{
|
|
webSocket.Close();
|
|
webSocket = null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 与WebSocket服务器的连接建立
|
|
/// </summary>
|
|
/// <param name="ws"></param>
|
|
void OnOpen(WebSocket ws)
|
|
{
|
|
Debug.Log("后端连接成功");
|
|
webSocket.Send("后端连接成功");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从服务器接收到新的文本消息时
|
|
/// </summary>
|
|
/// <param name="ws"></param>
|
|
/// <param name="message"></param>
|
|
void OnMessageRecv(WebSocket ws, string message)
|
|
{
|
|
Debug.LogFormat("接收到:{0}", message);
|
|
LocalVideo.Inst.Dispose(message);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从服务器接收到新的二进制消息时
|
|
/// </summary>
|
|
/// <param name="ws"></param>
|
|
/// <param name="data"></param>
|
|
void OnBinaryRecv(WebSocket ws, byte[] data)
|
|
{
|
|
Debug.LogFormat("接收到(二进制):{0}", data.Length);
|
|
}
|
|
|
|
/// <summary>
|
|
/// WebSocket连接关闭时
|
|
/// </summary>
|
|
/// <param name="ws"></param>
|
|
/// <param name="code"></param>
|
|
/// <param name="message"></param>
|
|
void OnClosed(WebSocket ws, UInt16 code, string message)
|
|
{
|
|
Debug.LogFormat("连接关闭:{0}", message);
|
|
webSocket = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 遇到错误时
|
|
/// </summary>
|
|
/// <param name="ws"></param>
|
|
/// <param name="ex"></param>
|
|
void OnError(WebSocket ws, Exception ex)
|
|
{
|
|
string errorMsg = string.Empty;
|
|
#if !UNITY_WEBGL || UNITY_EDITOR
|
|
if (ws.InternalRequest.Response != null)
|
|
{
|
|
errorMsg = string.Format("服务器的状态码: {0} 消息: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
|
|
}
|
|
#endif
|
|
Debug.LogFormat("OnError:错误发生: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
|
|
webSocket = null;
|
|
}
|
|
|
|
}
|