internal Task <string> GetAsync() { var tcs = new TaskCompletionSource <string>(); var client = new HttpClient(); var rtmUrl = "eohx7l4e.rtm.lncld.net"; var url = string.Format("https://{0}/v1/route?appId={1}&secure=1", rtmUrl, "Eohx7L4EMfe4xmairXeT7q1w-gzGzoHsz"); client.GetAsync(url).ContinueWith(t => { if (t.IsFaulted) { var exception = t.Exception.InnerException; AVRealtime.PrintLog("get router error: {0}", exception.Message); tcs.SetException(exception); return(null); } var content = t.Result.Content; return(content.ReadAsStringAsync()); }).Unwrap().ContinueWith(t => { AVRealtime.PrintLog("get router: {0}", t.Result); var res = JsonConvert.DeserializeObject(t.Result) as JObject; if (res.TryGetValue("server", out var serverObj)) { var server = serverObj.ToString(); tcs.SetResult(server); } else { tcs.SetException(new Exception("no server")); } }); return(tcs.Task); }
public Task TestConnectAsync() { var realtime = new AVRealtime("uay57kigwe0b6f5n0e1d4z4xhydsml3dor24bzwvzr57wdap", "kfgz7jjfsk55r5a8a3y4ttd3je1ko11bkibcikonk32oozww"); return realtime.CreateClient("junwu").ContinueWith(t => { var client = t.Result; Console.WriteLine(client.State.ToString()); return client; }).ContinueWith(s => { var client = s.Result; var admins = new string[] { "zman", "junwu" }; return client.CreateConversationAsync("abc", false, new Dictionary<string, object> { { "admins",admins } }); }).Unwrap().ContinueWith(c => { var conv = c.Result; Console.WriteLine(conv.ConversationId); foreach (var key in conv.Keys) { Console.WriteLine(conv[key]); } }); }
/// <summary> /// Open websocket connection. /// </summary> /// <returns>The async.</returns> /// <param name="secure">If set to <c>true</c> secure.</param> /// <param name="subprotocol">Subprotocol.</param> /// <param name="enforce">If set to <c>true</c> enforce.</param> /// <param name="cancellationToken">Cancellation token.</param> public Task <bool> OpenAsync(bool secure, string subprotocol = null, bool enforce = false, CancellationToken cancellationToken = default(CancellationToken)) { _secure = secure; if (state == Status.Online && !enforce) { AVRealtime.PrintLog("state is Status.Online."); return(Task.FromResult(true)); } if (CurrentConfiguration.RealtimeServer != null) { _wss = CurrentConfiguration.RealtimeServer.ToString(); AVRealtime.PrintLog("use configuration realtime server with url: " + _wss); return(OpenAsync(_wss, subprotocol, enforce)); } var routerUrl = CurrentConfiguration.RTMRouter != null?CurrentConfiguration.RTMRouter.ToString() : (AVClient.CurrentConfiguration.PushServer != null ? AVClient.CurrentConfiguration.PushServer.ToString() : null); return(RouterController.GetAsync(routerUrl, secure, cancellationToken).OnSuccess(r => { var routerState = r.Result; if (routerState == null) { return Task.FromResult(false); } _wss = routerState.server; _secondaryWss = routerState.secondary; state = Status.Connecting; AVRealtime.PrintLog("push router give a url :" + _wss); return OpenAsync(routerState.server, subprotocol, enforce); }).Unwrap()); }
void HandleJoinedConversation(GenericCommand command) { var clientId = command.peerId; var joinedConvCmd = command.convMessage; var initBy = joinedConvCmd.initBy; var cid = joinedConvCmd.Cid; if (Connection.idToClient.TryGetValue(clientId, out var client)) { // ???是不是应该把这个接口实现放到 Connection 中 Connection.QueryConversationAsync(clientId, cid).ContinueWith(t => { if (t.IsFaulted) { AVRealtime.PrintLog(t.Exception.InnerException.Message); } else { var conv = t.Result; AVRealtime.Context.Post(() => { client.HandleJoinedConversation(conv); }); } }); } else { // TODO 没有查找到对应 IM Client } }
/// <summary> /// 打开会话 /// </summary> /// <returns>The session.</returns> internal Task OpenSession(AVIMClient client) { var tcs = new TaskCompletionSource <bool>(); var sessionOpen = new SessionCommand { configBitmap = 1, Ua = "net-universal/1.0.6999.29889", N = null, T = 0, S = null, }; var cmd = commandFactory.NewRequest(client.ClientId, CommandType.Session, OpType.Open); cmd.sessionMessage = sessionOpen; SendRequest(cmd).ContinueWith(t => { AVRealtime.Context.Post(() => { if (t.IsFaulted) { AVRealtime.PrintLog("open session error"); tcs.SetException(t.Exception.InnerException); } else { var res = t.Result; var sessionOpened = res.sessionMessage; // TODO 判断会话打开结果 idToClient.Add(client.ClientId, client); tcs.SetResult(true); } }); }); return(tcs.Task); }
void HandleMembersLeft(GenericCommand command) { var clientId = command.peerId; var membersLeft = command.convMessage; var cid = membersLeft.Cid; var memberIds = membersLeft.M; if (Connection.idToClient.TryGetValue(clientId, out var client)) { if (client.idToConversation.TryGetValue(cid, out var conversation)) { client.HandleMemebersLeft(conversation, memberIds); } else { Connection.QueryConversationAsync(clientId, cid).ContinueWith(t => { if (t.IsFaulted) { AVRealtime.PrintLog(t.Exception.InnerException.Message); } else { var conv = t.Result; AVRealtime.Context.Post(() => { client.HandleMemebersLeft(conversation, memberIds); }); } }); } } else { // TODO 没有查找到对应 IM Client } }
/// <summary> /// 打开 WebSocket 链接 /// </summary> /// <param name="wss">websocket server address</param> /// <param name="cancellationToken"></param> /// <returns></returns> internal Task OpenAsync(string wss, CancellationToken cancellationToken = default(CancellationToken)) { AVRealtime.PrintLog(wss + " connecting..."); var tcs = new TaskCompletionSource <bool>(); Action <string> onError = null; onError = ((reason) => { PCLWebsocketClient.OnError -= onError; tcs.SetResult(false); tcs.TrySetException(new AVIMException(AVIMException.ErrorCode.FromServer, "try to open websocket at " + wss + "failed.The reason is " + reason, null)); }); Action onOpend = null; onOpend = (() => { PCLWebsocketClient.OnError -= onError; PCLWebsocketClient.OnOpened -= onOpend; tcs.SetResult(true); AVRealtime.PrintLog(wss + " connected."); }); PCLWebsocketClient.OnOpened += onOpend; PCLWebsocketClient.OnError += onError; PCLWebsocketClient.Open(wss); return(tcs.Task); }
void WebSocketClient_OnMessage(GenericCommand cmd) { AVRealtime.Context.Post(() => { if (cmd.ShouldSerializeI()) { // 应答消息 var reqId = cmd.I; if (requests.TryGetValue(reqId, out var tcs)) { tcs.SetResult(cmd); requests.Remove(reqId); } else { // 没有缓存的应答 } } else { // 通知消息 if (cmdToHandler.TryGetValue(cmd.Cmd, out var handler)) { try { handler.Handle(cmd); } catch (Exception e) { AVRealtime.PrintLog(e.Message); } } else { AVRealtime.PrintLog("No handler for cmd: {0}", cmd.Cmd); } } }); }
internal override void Handle(GenericCommand command) { var recvMsg = command.directMessage; // 获取到 IM Client var clientId = command.peerId; if (Connection.idToClient.TryGetValue(clientId, out var client)) { // 再获取到 Conversation var convId = recvMsg.Cid; if (client.idToConversation.TryGetValue(convId, out var conversation)) { // 再通过 Conversation 和 Message 通知用户 client.HandleReceiveMessage(conversation, new AVIMTextMessage { Text = "fake cached message" }); } else { Connection.QueryConversationAsync(clientId, convId).ContinueWith(t => { if (t.IsFaulted) { AVRealtime.PrintLog(t.Exception.InnerException.Message); return; } AVRealtime.Context.Post(() => { client.HandleReceiveMessage(conversation, new AVIMTextMessage { Text = "fake queried message" }); }); }); } } }
public static void PrintLog(string log) { if (AVRealtime.LogTracker != null) { AVRealtime.LogTracker(log); } }
/// <summary> /// 创建 Client /// </summary> /// <param name="clientId"></param> /// <param name="tag"></param> /// <param name="deviceId">设备唯一的 Id。如果是 iOS 设备,需要将 iOS 推送使用的 DeviceToken 作为 deviceId 传入</param> /// <param name="secure">是否强制加密 wss 链接</param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <AVIMClient> CreateClientAsync(string clientId, string tag = null, string deviceId = null, bool secure = true, CancellationToken cancellationToken = default(CancellationToken)) { lock (mutex) { var client = PreLogIn(clientId, tag, deviceId); AVRealtime.PrintLog("begin OpenAsync."); return(OpenAsync(secure, Subprotocol, true, cancellationToken).OnSuccess(t => { if (!t.Result) { return Task.FromResult <AVIMCommand>(null); } AVRealtime.PrintLog("websocket server connected, begin to open sesstion."); SetNetworkState(); var cmd = new SessionCommand() .UA(VersionString) .Tag(tag) .DeviceId(deviceId) .Option("open") .PeerId(clientId); ToggleNotification(true); return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId)); }).Unwrap().OnSuccess(x => { var cmd = x.Result; if (cmd == null) { return Task.FromResult <Tuple <int, IDictionary <string, object> > >(null); } return this.RunCommandAsync(cmd); }).Unwrap().OnSuccess(s => { if (s.Result == null) { return null; } AVRealtime.PrintLog("sesstion opened."); state = Status.Online; ToggleHeartBeating(true); var response = s.Result.Item2; if (response.ContainsKey("st")) { _sesstionToken = response["st"] as string; } if (response.ContainsKey("stTtl")) { var stTtl = long.Parse(response["stTtl"].ToString()); _sesstionTokenExpire = DateTime.Now.ToUnixTimeStamp() + stTtl * 1000; } AfterLogIn(client); return client; })); } }
//public void On(string eventName, Action<IDictionary<string, object>> data) //{ //} private void WebSocketClient_OnMessage(string obj) { AVRealtime.PrintLog("websocket<=" + obj); var estimatedData = Json.Parse(obj) as IDictionary <string, object>; var notice = new AVIMNotice(estimatedData); m_NoticeReceived?.Invoke(this, notice); }
internal GenericCommand NewRequest(string clientId, CommandType cmd, OpType op) { var request = NewCommand(clientId, cmd, op); request.I = RequestId; AVRealtime.PrintLog("request I op: {0}", request.I); return(request); }
internal void Send(GenericCommand cmd) { AVRealtime.PrintLog("websocket=>{0}", JsonConvert.SerializeObject(cmd)); using (var ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize(ms, cmd); ms.Position = 0; var msg = Convert.ToBase64String(ms.ToArray()); ws.Send(msg); } }
// WebSocket 事件 void OnWebSocketMessage(string msg) { //AVRealtime.PrintLog("websocket<={0}", msg); // TODO 考虑是否要做反序列化??? byte[] byteArray = Convert.FromBase64String(msg); var cmd = ProtoBuf.Serializer.Deserialize <GenericCommand>(new MemoryStream(byteArray)); AVRealtime.PrintLog("websocket<={0}", JsonConvert.SerializeObject(cmd)); OnMessage?.Invoke(cmd); }
internal override void Handle(GenericCommand command) { Connection.ClearCache().ContinueWith(t => { if (t.IsFaulted) { AVRealtime.PrintLog(t.Exception.InnerException.Message); return; } Connection.Disconnect(); }); }
internal void HandleReconnected() { connection.ReOpenSession(ClientId).ContinueWith(t => { if (t.IsFaulted) { AVRealtime.PrintLog(t.Exception.InnerException.Message); return; } // IM Client 重连完成 OnReconnected?.Invoke(); }); }
/// <summary> /// /// </summary> /// <param name="clientId"></param> /// <param name="tag"></param> /// <param name="realtime"></param> internal AVIMClient(string clientId, string tag, AVRealtime realtime) { this.clientId = clientId; Tag = tag ?? tag; _realtime = realtime; #region sdk 强制在接收到消息之后一定要向服务端回发 ack var ackListener = new AVIMMessageListener(); ackListener.OnMessageReceived += AckListener_OnMessageReceieved; //this.RegisterListener(ackListener); #endregion #region 默认要为当前 client 绑定一个消息的监听器,用作消息的事件通知 var messageListener = new AVIMMessageListener(); messageListener.OnMessageReceived += MessageListener_OnMessageReceived; this.RegisterListener(messageListener); #endregion #region 默认要为当前 client 绑定一个 session close 的监听器,用来监测单点登录冲突的事件通知 var sessionListener = new SessionListener(); sessionListener.OnSessionClosed += SessionListener_OnSessionClosed; this.RegisterListener(sessionListener); #endregion #region 默认要为当前 client 监听 Ta 所出的对话中的人员变动的被动消息通知 var membersJoinedListener = new AVIMMembersJoinListener(); membersJoinedListener.OnMembersJoined += MembersJoinedListener_OnMembersJoined; this.RegisterListener(membersJoinedListener); var membersLeftListener = new AVIMMembersLeftListener(); membersLeftListener.OnMembersLeft += MembersLeftListener_OnMembersLeft; this.RegisterListener(membersLeftListener); var invitedListener = new AVIMInvitedListener(); invitedListener.OnInvited += InvitedListener_OnInvited; this.RegisterListener(invitedListener); var kickedListener = new AVIMKickedListener(); kickedListener.OnKicked += KickedListener_OnKicked; this.RegisterListener(kickedListener); #endregion #region 当前 client id 离线的时间内,TA 所在的对话产生的普通消息会以离线消息的方式送达到 TA 下一次登录的客户端 var offlineMessageListener = new OfflineMessageListener(); offlineMessageListener.OnOfflineMessageReceived += OfflineMessageListener_OnOfflineMessageReceived; this.RegisterListener(offlineMessageListener); #endregion #region 当前 client 离线期间内产生的未读消息可以通过之后调用 Conversation.SyncStateAsync 获取一下离线期间内的未读状态 var unreadListener = new ConversationUnreadListener(); this.RegisterListener(unreadListener); #endregion }
/// <summary> /// open webcoket connection with cloud. /// </summary> /// <param name="url">wss address</param> /// <param name="subprotocol">subprotocol for websocket</param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <bool> OpenAsync(string url, string subprotocol = null, bool enforce = false, CancellationToken cancellationToken = default(CancellationToken)) { if (AVWebSocketClient.IsOpen && !enforce) { AVRealtime.PrintLog(url + "is already connectd."); return(Task.FromResult(true)); } AVRealtime.PrintLog("websocket try to connect url :" + url + " with subprotocol: " + subprotocol); AVRealtime.PrintLog(url + " \tconnecting..."); return(AVWebSocketClient.Connect(url, subprotocol)); }
/// <summary> /// 打开会话 /// </summary> /// <returns>The open.</returns> public Task Open() { return(AVRealtime.GetConnection("Eohx7L4EMfe4xmairXeT7q1w-gzGzoHsz").ContinueWith(t => { if (t.IsFaulted) { AVRealtime.PrintLog(t.Exception.InnerException.Message); var tcs = new TaskCompletionSource <bool>(); tcs.SetException(t.Exception.InnerException); return tcs.Task; } // TODO 在 SDK 上下文中设置 connection = t.Result; return connection.OpenSession(this); }).Unwrap()); }
/// <summary> /// open webcoket connection with cloud. /// </summary> /// <param name="url">wss address</param> /// <param name="subprotocol">subprotocol for websocket</param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <bool> OpenAsync(string url, string subprotocol = null, CancellationToken cancellationToken = default(CancellationToken)) { if (PCLWebsocketClient.IsOpen) { AVRealtime.PrintLog(url + "is already connectd."); return(Task.FromResult(true)); } AVRealtime.PrintLog("websocket try to connect url :" + url + "with subprotocol: " + subprotocol); AVRealtime.PrintLog(url + " connecting..."); var tcs = new TaskCompletionSource <bool>(); Action <string> onError = null; onError = ((reason) => { PCLWebsocketClient.OnError -= onError; tcs.TrySetResult(false); tcs.TrySetException(new AVIMException(AVIMException.ErrorCode.FromServer, "try to open websocket at " + url + "failed.The reason is " + reason, null)); }); Action onOpend = null; onOpend = (() => { PCLWebsocketClient.OnError -= onError; PCLWebsocketClient.OnOpened -= onOpend; tcs.TrySetResult(true); AVRealtime.PrintLog(url + " connected."); }); Action <int, string, string> onClosed = null; onClosed = (reason, arg0, arg1) => { PCLWebsocketClient.OnError -= onError; PCLWebsocketClient.OnOpened -= onOpend; PCLWebsocketClient.OnClosed -= onClosed; tcs.TrySetResult(false); tcs.TrySetException(new AVIMException(AVIMException.ErrorCode.FromServer, "try to open websocket at " + url + "failed.The reason is " + reason, null)); }; PCLWebsocketClient.OnOpened += onOpend; PCLWebsocketClient.OnClosed += onClosed; PCLWebsocketClient.OnError += onError; PCLWebsocketClient.Open(url, subprotocol); return(tcs.Task); }
/// <summary> /// websocket 事件的监听的开关 /// </summary> /// <param name="toggle">是否打开</param> public void ToggleNotification(bool toggle) { AVRealtime.PrintLog("ToggleNotification| toggle:" + toggle + "|listening: " + _listening); if (toggle && !_listening) { AVWebSocketClient.OnClosed += WebsocketClient_OnClosed; AVWebSocketClient.OnMessage += WebSocketClient_OnMessage; _listening = true; } else if (!toggle && _listening) { AVWebSocketClient.OnClosed -= WebsocketClient_OnClosed; AVWebSocketClient.OnMessage -= WebSocketClient_OnMessage; _listening = false; } }
/// <summary> /// 创建 Client /// </summary> /// <param name="clientId"></param> /// <param name="tag"></param> /// <param name="deviceId">设备唯一的 Id。如果是 iOS 设备,需要将 iOS 推送使用的 DeviceToken 作为 deviceId 传入</param> /// <param name="secure">是否强制加密 wss 链接</param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task <AVIMClient> CreateClientAsync(string clientId, string tag = null, string deviceId = null, bool secure = true, CancellationToken cancellationToken = default(CancellationToken)) { lock (mutex) { var client = PreLogIn(clientId, tag, deviceId); AVRealtime.PrintLog("begin OpenAsync."); return(OpenAsync(secure, Subprotocol, cancellationToken).OnSuccess(t => { AVRealtime.PrintLog("OpenAsync OnSuccess. begin send open sesstion cmd."); var cmd = new SessionCommand() .UA(VersionString) .Tag(tag) .DeviceId(deviceId) .Option("open") .PeerId(clientId); ToggleNotification(true); return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId)); }).Unwrap().OnSuccess(x => { var cmd = x.Result; return AVIMCommandRunner.RunCommandAsync(cmd); }).Unwrap().OnSuccess(s => { AVRealtime.PrintLog("sesstion opened."); state = Status.Online; ToggleHeartBeating(_heartBeatingToggle); var response = s.Result.Item2; if (response.ContainsKey("st")) { _sesstionToken = response["st"] as string; } if (response.ContainsKey("stTtl")) { var stTtl = long.Parse(response["stTtl"].ToString()); _sesstionTokenExpire = DateTime.Now.UnixTimeStampSeconds() + stTtl; } return client; })); } }
internal Task Open(string url, string protocol = null) { AVRealtime.PrintLog("websocket open"); var tcs = new TaskCompletionSource <bool>(); void onOpen() { AVRealtime.PrintLog("websocket opened"); ws.OnOpened -= onOpen; ws.OnClosed -= onClose; ws.OnError -= onError; ws.OnMessage += OnWebSocketMessage; ws.OnClosed += OnWebSocketDisconnected; ws.OnError += OnWebSocketError; tcs.SetResult(true); } void onClose() { ws.OnOpened -= onOpen; ws.OnClosed -= onClose; ws.OnError -= onError; tcs.SetException(new Exception("websocket closed when open")); } void onError(string err) { ws.OnOpened -= onOpen; ws.OnClosed -= onClose; ws.OnError -= onError; tcs.SetException(new Exception(string.Format("websocket open error: {0}", err))); } try { ws = WebSocketFactory.Create(); } catch (Exception e) { AVRealtime.PrintLog(e.Message); } ws.OnOpened += onOpen; ws.OnClosed += onClose; ws.OnError += onError; url = string.Format("{0}?subprotocol=lc.proto2base64.3", "wss://rtm51.leancloud.cn"); AVRealtime.PrintLog("connect: {0}", url); ws.Open(url); return(tcs.Task); }
internal Task LogInAsync(string clientId, string tag = null, string deviceId = null, bool secure = true, CancellationToken cancellationToken = default(CancellationToken)) { lock (mutex) { var cmd = new SessionCommand() .UA(VersionString) .Tag(tag) .DeviceId(deviceId) .Option("open") .PeerId(clientId); var result = AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId)).OnSuccess(_ => { return(RunCommandAsync(cmd)); }).Unwrap().OnSuccess(t => { AVRealtime.PrintLog("sesstion opened."); if (t.Exception != null) { var imException = t.Exception.InnerException as AVIMException; throw imException; } state = Status.Online; var response = t.Result.Item2; if (response.ContainsKey("st")) { _sesstionToken = response["st"] as string; } if (response.ContainsKey("stTtl")) { var stTtl = long.Parse(response["stTtl"].ToString()); _sesstionTokenExpire = DateTime.Now.ToUnixTimeStamp() + stTtl * 1000; } return(t.Result); }); return(result); } }
private void SessionListener_OnSessionClosed(int arg1, string arg2, string arg3) { if (m_OnSessionClosed != null) { var args = new AVIMSessionClosedEventArgs() { Code = arg1, Reason = arg2, Detail = arg3 }; if (args.Code == 4115 || args.Code == 4111) { this._realtime.sessionConflict = true; } m_OnSessionClosed(this, args); } AVRealtime.PrintLog("SessionListener_OnSessionClosed invoked."); //this.LinkedRealtime.LogOut(); }
/// <summary> /// 初始化实时消息客户端 /// </summary> /// <param name="config"></param> public AVRealtime(Configuration config) { lock (mutex) { AVClient.Initialize(config.ApplicationId, config.ApplicationKey); CurrentConfiguration = config; if (CurrentConfiguration.WebSocketClient != null) { AVIMCorePlugins.Instance.WebSocketController = CurrentConfiguration.WebSocketClient; } if (CurrentConfiguration.SignatureFactory != null) { this.SignatureFactory = CurrentConfiguration.SignatureFactory; } RegisterMessageType <AVIMMessage>(); RegisterMessageType <AVIMTypedMessage>(); RegisterMessageType <AVIMTextMessage>(); } _instance = this; }
/// <summary> /// Creates the client async. /// </summary> /// <returns>The client async.</returns> /// <param name="user">User.</param> /// <param name="tag">Tag.</param> /// <param name="deviceId">Device identifier.</param> /// <param name="secure">If set to <c>true</c> secure.</param> public Task <AVIMClient> CreateClientAsync(AVUser user = null, string tag = null, string deviceId = null, bool secure = true, CancellationToken cancellationToken = default(CancellationToken)) { AVIMClient client = null; AVRealtime.PrintLog("begin OpenAsync."); return(OpenAsync(secure, Subprotocol, true, cancellationToken).OnSuccess(openTask => { AVRealtime.PrintLog("OpenAsync OnSuccess. begin send open sesstion cmd."); var userTask = Task.FromResult(user); if (user == null) { userTask = AVUser.GetCurrentUserAsync(); } return userTask; }).Unwrap().OnSuccess(u => { var theUser = u.Result; return AVCloud.RequestRealtimeSignatureAsync(theUser); }).Unwrap().OnSuccess(signTask => { var signResult = signTask.Result; var clientId = signResult.ClientId; var nonce = signResult.Nonce; var singnature = signResult.Signature; var ts = signResult.Timestamp; client = PreLogIn(clientId, tag, deviceId); ToggleNotification(true); return this.OpenSessionAsync(clientId, tag, deviceId, nonce, ts, singnature, secure); }).Unwrap().OnSuccess(s => { ToggleHeartBeating(true); AfterLogIn(client); return client; })); }
void PrepareReconnect() { AVRealtime.PrintLog("Prepare Reconnect"); var checkNetAvailableTimer = new AVTimer(); checkNetAvailableTimer.Interval = 5000; var handler = new EventHandler <TimerEventArgs>((object sender, TimerEventArgs e) => { bool netAvailable = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); AVRealtime.PrintLog($"current net available: {netAvailable}"); if (netAvailable) { StartManualReconnect(); AVTimer timer = (AVTimer)sender; timer.Stop(); } }); checkNetAvailableTimer.Elapsed += handler; checkNetAvailableTimer.Start(); checkNetAvailableTimer.Enabled = true; }
internal Task OpenSessionAsync(string clientId, string tag = null, string deviceId = null, string nonce = null, long timestamp = 0, string signature = null, bool secure = true) { var cmd = new SessionCommand() .UA(VersionString) .Tag(tag) .DeviceId(deviceId) .Option("open") .PeerId(clientId) .Argument("n", nonce) .Argument("t", timestamp) .Argument("s", signature); return(RunCommandAsync(cmd).OnSuccess(t => { AVRealtime.PrintLog("sesstion opened."); if (t.Exception != null) { var imException = t.Exception.InnerException as AVIMException; throw imException; } state = Status.Online; var response = t.Result.Item2; if (response.ContainsKey("st")) { _sesstionToken = response["st"] as string; } if (response.ContainsKey("stTtl")) { var stTtl = long.Parse(response["stTtl"].ToString()); _sesstionTokenExpire = DateTime.Now.ToUnixTimeStamp() + stTtl * 1000; } return t.Result; })); }
void PrepareReconnect() { AVRealtime.PrintLog("Prepare Reconnect"); Task.Delay(RECONNECT_DELAY).ContinueWith(_ => { // 开启重连 AutoReconnect().ContinueWith(t => { if (t.IsFaulted) { // 重连失败,延迟再次重连 reconnectTimes++; AVRealtime.PrintLog(String.Format("reconnect {0} times", reconnectTimes)); if (reconnectTimes >= RECONNECT_FROM_APP_ROUTER) { // 如果大于当前服务地址的最大重连次数,则清空 Router 后重新重连 RouterController.ClearCache().ContinueWith(__ => { reborn = true; PrepareReconnect(); }); } else if (reconnectTimes >= RECONNECT_USE_SECONDARY_TIMES) { // 如果大于单台 IM 服务器的重连次数,则启用备用服务器 useSecondary = true; PrepareReconnect(); } else { PrepareReconnect(); } } else { // 重连成功 reconnectTimes = 0; reborn = false; useSecondary = false; } }); }); }
public Task TestSave() { //AVClient.Initialize("3knLr8wGGKUBiXpVAwDnryNT-gzGzoHsz", "3RpBhjoPXJjVWvPnVmPyFExt"); //var avObject = new AVObject("TestObject"); //avObject["key"] = "value"; //return avObject.SaveAsync().ContinueWith(t => // { // Console.WriteLine(avObject.ObjectId); // return Task.FromResult(0); // }).Unwrap(); Websockets.Net.WebsocketConnection.Link(); var realtime = new AVRealtime("3knLr8wGGKUBiXpVAwDnryNT-gzGzoHsz", "3RpBhjoPXJjVWvPnVmPyFExt"); return realtime.CreateClient("junwu").ContinueWith(t => { var client = t.Result; Console.WriteLine(client.State.ToString()); return Task.FromResult(0); }).Unwrap(); }