public static void GetBarrageServerInfo(int roomId, out IPEndPoint[] barrageServers, out int groupId) { barrageServers = null; groupId = 0; RoomId = roomId; // 如果计时器已经启动, 先停掉它, 确保其不能发送数据 if (_keepliveTimer != null) { _keepliveTimer.Stop(); } // 获取斗鱼服务器 LogService.Info("获取斗鱼服务器"); var servers = GetServers(roomId); // 连接斗鱼服务器 Exception exception = null; foreach (var server in servers) { try { LogService.InfoFormat("连接到斗鱼服务器: {0}", server.ToString()); exception = null; _douyuSocket = new DouyuSocket(); var host = server.Split(':')[0]; var port = int.Parse(server.Split(':')[1]); _douyuSocket.Connect(host, port); } catch (Exception ex) { exception = ex; } if (exception == null) { break; } } if (exception != null) { throw new DouyuException("连接斗鱼服务器失败!", exception); } LogService.Info("发送登录消息"); _douyuSocket.SendMessage(new LoginreqMessage(roomId)); LogService.Info("获取弹幕服务器"); barrageServers = GetBarrageServers(); groupId = -9999; // 海量弹幕 //LogService.Info("获取弹幕分组"); //groupId = GetMessageGroup(); if (_keepliveTimer == null) { _keepliveTimer = new System.Timers.Timer(45 * 1000); _keepliveTimer.Elapsed += KeepliveTimer_Elapsed; _keepliveTimer.Start(); } }
void LoginRoom() { LogService.Info("发送登录房间消息"); _douyuSocket.SendMessage(new LoginreqMessage(RoomId)); // 取消检查响应登录功能, 因为: // 首次连接服务器, 可以收到登录响应. 但是断开之后再连接, 有可能收不到 // 另外有时候服务器会不响应登录信息 //const long LOGIN_TIMEOUT = 20000; //var loginres = ""; //var watch = Stopwatch.StartNew(); //do { // if (_socket.Available > 0 && TryGetMessage(out loginres) && loginres.Contains("type@=loginres")) break; // MyApplication.Delay(100); //} while (watch.ElapsedMilliseconds < LOGIN_TIMEOUT); //if (loginres == null || !loginres.Contains("type@=loginres")) { // LogService.Fatal("服务器没有响应登录信息!"); // throw new DouyuException("服务器没有响应登录信息!"); //} }
static void KeepliveTimer_Elapsed(object sender, ElapsedEventArgs e) { try { _douyuSocket.SendMessage(new KeepliveMessage()); // 服务器会发送数据过来, 收了吧 var messageText = ""; _douyuSocket.TryGetMessage(out messageText); } catch (Exception ex) { LogService.Error("发送心跳信息失败!", ex); _keepliveTimer.Stop(); _keepliveTimer.Elapsed -= KeepliveTimer_Elapsed; _keepliveTimer = null; IPEndPoint[] barrageServers; int groupId; GetBarrageServerInfo(RoomId, out barrageServers, out groupId); } }