/// <summary> /// 心跳包监控 /// </summary> /// <param name="obj"></param> async void DanmmuKeepAlive(CancellationToken token) { byte[] aliveMsg = DataToBytes("type@=mrkl/"); await Task.Run(async() => { while (true) { try { if (token.IsCancellationRequested) { return; } AppLog.Info($"弹幕服务器【房间{ROOM_ID}】【发送心跳包】"); DanmuClient.Send(aliveMsg); await Task.Delay(30000); } catch (Exception ex) { //if (DanmuClient == null|| DanmuClient.ReadyState!= WebSocketState.Open) // return; AppLog.Error("心跳异常", ex); //if (!token.IsCancellationRequested) // Reconnect(); return; } } }); }
/// <summary> /// 登录房间 /// </summary> private void RoomLogin() { //string login = "******" + ROOM_ID + "/"; string login = $"type@=loginreq/roomid@={ROOM_ID}/dfl@=sn@AA=105@ASss@AA=1/username@={username}/uid@={userid}/ver@=20190610/aver@=218101901/ct@=0/"; byte[] loginBytes = DataToBytes(login); DanmuClient.Send(loginBytes); string joingroup = "type@=joingroup/rid@=" + ROOM_ID + "/gid@=-9999/"; byte[] joingroupBytes = DataToBytes(joingroup); DanmuClient.Send(joingroupBytes); AppLog.Debug($"登录房间【{ROOM_ID}】成功"); }
/// <summary> /// 释放资源 /// </summary> public void Dispose() { Console.WriteLine($"开始退出房间【{ROOM_ID}】"); source.Cancel(); AuthClient?.CloseAsync(); DanmuClient?.CloseAsync(); AuthClient = null; DanmuClient = null; if (agent != null) { agent.RemoveRoom(ROOM_ID); } Console.WriteLine($"结束监控房间【{ROOM_ID}】"); }
/// <summary> /// 初始化连接是否成功 /// </summary> /// <returns></returns> public bool Initialization() { try { //取消之前正在运行的线程 if (source != null) { source.Cancel(); } source = new CancellationTokenSource(); agent?.RemoveRoom(ROOM_ID); var ips = AgentPool.GetAgentIp(ROOM_ID); if (ips.Count > 0) { agent = ips[0]; Console.WriteLine($"{agent.Ip}:{agent.Port}"); } else { agent = null; } AuthClient?.CloseAsync(); DanmuClient?.CloseAsync(); //创建实例 AuthClient = CreateAuthSocket(source.Token); //认证 Authentication(); //认证通过开启心跳 AuthKeepAlive(source.Token); DanmuClient = CreateDanmuSocket(source.Token); //tcpClient = SocketHelper.InitTcp(agent.Ip, agent.Port); //ConnectProxyServer(SERVER_DOMAIN, SERVER_PORT, tcpClient); //登录房间 RoomLogin(); //心跳维持 DanmmuKeepAlive(source.Token); AppLog.Debug($"监控房间【{ROOM_ID}】成功"); return(true); } catch (Exception ex) { AppLog.Error($"【房间:{ROOM_ID}】【监控失败】", ex); return(false); } }