| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- using UnityEngine;
- using BestHTTP;
- using BestHTTP.WebSocket;
- using System;
- namespace DTYJ
- {
- public class ClientWebSocket
- {
- public ClientWebSocket(string address, OnWebSocketOpenDelegate onOpen, OnWebSocketMessageDelegate onMessage, OnWebSocketClosedDelegate onClose, OnWebSocketErrorDelegate onError)
- {
- this.address = address;
- this.onOpen = onOpen;
- this.onMessage = onMessage;
- this.onClose = onClose;
- this.onError = onError;
- }
- OnWebSocketOpenDelegate onOpen; OnWebSocketMessageDelegate onMessage; OnWebSocketClosedDelegate onClose; OnWebSocketErrorDelegate onError;
- public WebSocket webSocket;
- private string address;
- public void Connect()
- {
- // Create the WebSocket instance
- this.webSocket = new WebSocket(new Uri(address));
- #if !UNITY_WEBGL || UNITY_EDITOR
- this.webSocket.StartPingThread = true;
- //this.webSocket.StartPingThread = false;
- #if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR)
- if (HTTPManager.Proxy != null)
- this.webSocket.OnInternalRequestCreated = (ws, internalRequest) => internalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
- #endif
- #endif
- // Subscribe to the WS events
- this.webSocket.OnOpen += OnOpen;
- this.webSocket.OnMessage += OnMessageReceived;
- this.webSocket.OnClosed += OnClosed;
- this.webSocket.OnError += OnError;
- // Start connecting to the server
- this.webSocket.Open();
- //strBtnConnction = ("Connecting...");
- }
- #region WebSocket Event Handlers
- /// <summary>
- /// Called when the web socket is open, and we are ready to send and receive data
- /// </summary>
- void OnOpen(WebSocket ws)
- {
- //strBtnConnction = ("Á¬½Ó³É¹¦!");
- onOpen.Invoke(ws);
- }
- /// <summary>
- /// Called when we received a text message from the server
- /// </summary>
- void OnMessageReceived(WebSocket ws, string message)
- {
- //resMsg = $"{DateTime.Now.ToLongTimeString()}: {message}\n" + resMsg;
- onMessage?.Invoke(ws, message);
- }
- /// <summary>
- /// Called when the web socket closed
- /// </summary>
- void OnClosed(WebSocket ws, UInt16 code, string message)
- {
- //resMsg = (string.Format("WebSocket closed! Code: {0} Message: {1}\n", code, message)) + resMsg;
- webSocket = null;
- //strBtnConnction = "Á¬½Ó";
- onClose?.Invoke(ws, code, message);
- }
- /// <summary>
- /// Called when an error occured on client side
- /// </summary>
- void OnError(WebSocket ws, string error)
- {
- //resMsg = (string.Format("An error occured: {0}\n", error)) + resMsg;
- webSocket = null;
- //strBtnConnction = "Á¬½Ó";
- onError?.Invoke(ws, error);
- }
- #endregion
- public void SendMsg(string msg)
- {
- webSocket?.Send(msg);
- }
- }
- }
|