usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingBestHTTP;usingBestHTTP.WebSocket;usingSystem;usingBestHTTP.Examples;usingUnityEngine.UI;usingSystem.Text;public classWSMgr : MonoBehaviour
{//public string url = "ws://localhost:8080/web1/websocket";
[SerializeField]private stringurl;publicInputField msg;publicText console;privateWebSocket webSocket;private voidStart()
{
init();
print("执行");//WebSocket1();
}voidUpdate()
{
print(webSocket.IsOpen);
}voidWebSocket1()
{
WebSocket webSocket= new WebSocket(newUri(url));//webSocket.OnOpen...//注册事件之后,我们就可以开始连接
webSocket.Open();//在这一步之后,我们将收到一个OnOpen事件,我们可以开始发送消息到服务器
webSocket.Send("Message to the Server");byte[] buffer = new byte[1024];
webSocket.Send(buffer);//所有通信完成之后,就关闭连接
webSocket.Close();
}private voidinit()
{
webSocket= new WebSocket(newUri(url));
webSocket.OnOpen+=OnOpen;
webSocket.OnMessage+=OnMessageReceived;
webSocket.OnError+=OnError;
webSocket.OnClosed+=OnClosed;
webSocket.Open();
print("执行这里");
}private voidantiInit()
{
webSocket.OnOpen= null;
webSocket.OnMessage= null;
webSocket.OnError= null;
webSocket.OnClosed= null;
webSocket= null;
}private void setConsoleMsg(stringmsg)
{
console.text= "Message:" +msg;
}public voidConnect()
{
webSocket.Open();
print(webSocket!=null);
}private byte[] getBytes(stringmessage)
{byte[] buffer =Encoding.Default.GetBytes(message);returnbuffer;
}public voidSend()
{
webSocket.Send(msg.text);
}public void Send(stringstr)
{
webSocket.Send(str);
}public voidClose()
{
webSocket.Close();
}#region WebSocket Event Handlers
///
///Called when the web socket is open, and we are ready to send and receive data///
voidOnOpen(WebSocket ws)
{
Debug.Log("connected");
setConsoleMsg("Connected");
}///
///Called when we received a text message from the server///
void OnMessageReceived(WebSocket ws, stringmessage)
{
Debug.Log(message);
setConsoleMsg(message);
}///
///Called when the web socket closed///
void OnClosed(WebSocket ws, UInt16 code, stringmessage)
{
Debug.Log(message+ "close");//setConsoleMsg(message);//antiInit();//init();
}//void OnApplicationQuit
voidOnApplicationQuit()
{//print(webSocket.IsOpen);//if (webSocket != null && webSocket.IsOpen)//{
print("quit");//webSocket.Close();// //antiInit();//}
}private voidOnDestroy()
{
print("destory");//if (webSocket != null && webSocket.IsOpen)//{//print("destory");//webSocket.Close();// //antiInit();//}
}///
///Called when an error occured on client side///
voidOnError(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);#endifDebug.Log(errorMsg);
setConsoleMsg(errorMsg);//antiInit();//init();
}#endregion}