private void OnClose(object sender, CloseEventArgs e) { AVRealtime.PrintLog("Unity websocket closed without parameters."); if (this.OnClosed != null) { this.OnClosed(e.Code, e.Reason, ""); } }
private void Connection_OnClosed() { AVRealtime.PrintLog("PCL websocket closed without parameters."); if (this.OnClosed != null) { this.OnClosed(0, "", ""); } }
private void CallOnDisconnected() { AVRealtime.PrintLog("PCL websocket closed without parameters."); if (OnClosed != null) { RunInTask(() => this.OnClosed(0, "", "")); } }
public void RunCommand(AVIMCommand command) { command.IDlize(); var requestString = command.EncodeJsonString(); AVRealtime.PrintLog("websocket=>" + requestString); webSocketClient.Send(requestString); }
/// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <Tuple <int, IDictionary <string, object> > > RunCommandAsync(AVIMCommand command, CancellationToken cancellationToken = default(CancellationToken)) { var tcs = new TaskCompletionSource <Tuple <int, IDictionary <string, object> > >(); command.IDlize(); var requestString = command.EncodeJsonString(); if (!command.IsValid) { requestString = "{}"; } AVRealtime.PrintLog("websocket=>" + requestString); webSocketClient.Send(requestString); var requestJson = command.Encode(); Action <string> onMessage = null; onMessage = (response) => { //AVRealtime.PrintLog("response<=" + response); var responseJson = Json.Parse(response) as IDictionary <string, object>; if (responseJson.Keys.Contains("i")) { if (requestJson["i"].ToString() == responseJson["i"].ToString()) { var result = new Tuple <int, IDictionary <string, object> >(-1, responseJson); if (responseJson.Keys.Contains("code")) { var errorCode = int.Parse(responseJson["code"].ToString()); var reason = string.Empty; int appCode = 0; if (responseJson.Keys.Contains("reason")) { reason = responseJson["reason"].ToString(); } if (responseJson.Keys.Contains("appCode")) { appCode = int.Parse(responseJson["appCode"].ToString()); } tcs.SetException(new AVIMException(errorCode, appCode, reason, null)); } if (tcs.Task.Exception == null) { tcs.SetResult(result); } webSocketClient.OnMessage -= onMessage; } else { } } }; webSocketClient.OnMessage += onMessage; return(tcs.Task); }
public Task <bool> Connect(string url, string protocol = null) { var tcs = new TaskCompletionSource <bool>(); Action onOpen = null; Action onClose = null; Action <string> onError = null; onOpen = () => { AVRealtime.PrintLog("PCL websocket opened"); connection.OnOpened -= onOpen; connection.OnClosed -= onClose; connection.OnError -= onError; // 注册事件 connection.OnMessage += Connection_OnMessage; connection.OnClosed += Connection_OnClosed; connection.OnError += Connection_OnError; tcs.SetResult(true); }; onClose = () => { connection.OnOpened -= onOpen; connection.OnClosed -= onClose; connection.OnError -= onError; tcs.SetException(new Exception("连接关闭")); }; onError = (err) => { AVRealtime.PrintLog(string.Format("连接错误:{0}", err)); connection.OnOpened -= onOpen; connection.OnClosed -= onClose; connection.OnError -= onError; try { connection.Close(); } catch (Exception e) { AVRealtime.PrintLog(string.Format("关闭错误的 WebSocket 异常:{0}", e.Message)); } finally { tcs.SetException(new Exception(string.Format("连接错误:{0}", err))); } }; // 在每次打开时,重新创建 WebSocket 对象 connection = WebSocketFactory.Create(); connection.OnOpened += onOpen; connection.OnClosed += onClose; connection.OnError += onError; // if (!string.IsNullOrEmpty(protocol)) { url = string.Format("{0}?subprotocol={1}", url, protocol); } connection.Open(url, protocol); return(tcs.Task); }
public Task <bool> Connect(string url, string protocol = null) { var tcs = new TaskCompletionSource <bool>(); EventHandler onOpen = null; EventHandler <CloseEventArgs> onClose = null; EventHandler <ErrorEventArgs> onError = null; onOpen = (sender, e) => { AVRealtime.PrintLog("PCL websocket opened"); ws.OnOpen -= onOpen; ws.OnClose -= onClose; ws.OnError -= onError; // 注册事件 ws.OnMessage += OnWebSokectMessage; ws.OnClose += OnClose; ws.OnError += OnWebSocketError; tcs.SetResult(true); }; onClose = (sender, e) => { ws.OnOpen -= onOpen; ws.OnClose -= onClose; ws.OnError -= onError; tcs.SetException(new Exception("连接关闭")); }; onError = (sender, e) => { AVRealtime.PrintLog(string.Format("连接错误:{0}", e.Message)); ws.OnOpen -= onOpen; ws.OnClose -= onClose; ws.OnError -= onError; try { ws.Close(); } catch (Exception ex) { AVRealtime.PrintLog(string.Format("关闭错误的 WebSocket 异常:{0}", ex.Message)); } finally { tcs.SetException(new Exception(string.Format("连接错误:{0}", e.Message))); } }; // 在每次打开时,重新创建 WebSocket 对象 if (!string.IsNullOrEmpty(protocol)) { url = string.Format("{0}?subprotocol={1}", url, protocol); } ws = new WebSocket(url); ws.OnOpen += onOpen; ws.OnClose += onClose; ws.OnError += onError; ws.ConnectAsync(); return(tcs.Task); }
public void Close() { if (connection != null) { connection.OnOpened -= Connection_OnOpened; connection.OnMessage -= Connection_OnMessage; connection.OnClosed -= Connection_OnClosed; connection.OnError -= Connection_OnError; try { connection.Close(); } catch (Exception e) { AVRealtime.PrintLog(string.Format("close websocket error: {0}", e.Message)); } } }
public void Send(string message) { if (connection != null) { if (this.IsOpen) { connection.Send(message); } else { var log = "Connection is NOT open when send message"; AVRealtime.PrintLog(log); connection?.Close(); } } else { AVRealtime.PrintLog("Connection is NULL"); } }
private void Connection_OnError(string obj) { AVRealtime.PrintLog($"PCL websocket error: {obj}"); connection?.Close(); }
Task <PushRouterState> QueryAsync(string pushRouter, bool secure, CancellationToken cancellationToken) { var routerHost = pushRouter; if (routerHost == null) { var appRouter = AVPlugins.Instance.AppRouterController.Get(); routerHost = string.Format("https://{0}/v1/route?appId={1}", appRouter.RealtimeRouterServer, AVClient.CurrentConfiguration.ApplicationId) ?? appRouter.RealtimeRouterServer ?? string.Format(routerUrl, AVClient.CurrentConfiguration.ApplicationId); } AVRealtime.PrintLog($"router: {routerHost}"); AVRealtime.PrintLog($"push: {pushRouter}"); if (!string.IsNullOrEmpty(pushRouter)) { var rtmUri = new Uri(pushRouter); if (!string.IsNullOrEmpty(rtmUri.Scheme)) { var url = new Uri(rtmUri, "v1/route").ToString(); routerHost = string.Format("{0}?appId={1}", url, AVClient.CurrentConfiguration.ApplicationId); } else { routerHost = string.Format("https://{0}/v1/route?appId={1}", pushRouter, AVClient.CurrentConfiguration.ApplicationId); } } if (secure) { routerHost += "&secure=1"; } AVRealtime.PrintLog("use push router url:" + routerHost); return(AVClient.RequestAsync(uri: new Uri(routerHost), method: "GET", headers: null, data: null, contentType: "application/json", cancellationToken: CancellationToken.None).ContinueWith <PushRouterState>(t => { if (t.Exception != null) { var innnerException = t.Exception.InnerException.InnerException.InnerException; if (innnerException != null) { AVRealtime.PrintLog(innnerException.Message); return null; } } var httpStatus = (int)t.Result.Item1; if (httpStatus != 200) { return null; } try { var result = t.Result.Item2; var routerState = Json.Parse(result) as IDictionary <string, object>; if (routerState.Keys.Count == 0) { throw new KeyNotFoundException("Can not get websocket url from server,please check the appId."); } var ttl = long.Parse(routerState["ttl"].ToString()); var expire = DateTime.Now.AddSeconds(ttl); routerState["expire"] = expire.ToUnixTimeStamp(); //save to local cache async. AVPlugins.Instance.StorageController.LoadAsync().OnSuccess(storage => storage.Result.AddAsync(routerKey, routerState)); var routerStateObj = new PushRouterState() { groupId = routerState["groupId"] as string, server = routerState["server"] as string, secondary = routerState["secondary"] as string, ttl = long.Parse(routerState["ttl"].ToString()), expire = expire.ToUnixTimeStamp(), source = "online" }; return routerStateObj; } catch (Exception e) { if (e is KeyNotFoundException) { throw e; } return null; } })); }
private void Connection_OnMessage(string obj) { AVRealtime.PrintLog("websocket<=" + obj); OnMessage?.Invoke(obj); }
private void Connection_OnClosed() { AVRealtime.PrintLog("PCL websocket closed without parameters.."); OnClosed?.Invoke(0, "", ""); }
private void OnWebSokectMessage(object sender, MessageEventArgs e) { AVRealtime.PrintLog("websocket<=" + e.Data); m_OnMessage?.Invoke(e.Data); }
private void OnClose(object sender, CloseEventArgs e) { AVRealtime.PrintLog(string.Format("Unity websocket closed with {0}, {1}", e.Code, e.Reason)); OnClosed?.Invoke(e.Code, e.Reason, null); }
void OnWebSocketError(object sender, ErrorEventArgs e) { AVRealtime.PrintLog($"PCL websocket error: {e.Message}"); ws?.Close(); }
private void Realtime_OnOfflineMessageReceived(object sender, AVIMMessageEventArgs e) { AVRealtime.PrintLog(e.Message.Id); }
private void Connection_OnError(string obj) { AVRealtime.PrintLog($"PCL websocket error: {obj}"); OnError?.Invoke(obj); }