private bool InitConnection(DanmakuServer danmakuServer)
        {
            Json.Value initMsg = new Json.Value.Object
            {
                ["uid"]       = 0,
                ["roomid"]    = danmakuServer.RoomId,
                ["protover"]  = 2,
                ["platform"]  = "web",
                ["clientver"] = "1.12.0",
                ["type"]      = 2,
                ["key"]       = danmakuServer.Token
            };

            try
            {
                PackWriter.SendMessage((int)BiliPackWriter.MessageType.CONNECT, initMsg.ToString());
                return(true);
            }
            catch (SocketException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                return(false);
            }
            catch (InvalidOperationException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                return(false);
            }
            catch (IOException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                return(false);
            }
        }
        private ClientWebSocket GetWssConnection(DanmakuServer danmakuServer)
        {
            ClientWebSocket clientWebSocket = new ClientWebSocket();

            clientWebSocket.ConnectAsync(new Uri($"wss://{danmakuServer.Server}:{danmakuServer.WssPort}/sub"), CancellationToken.None).GetAwaiter().GetResult();
            return(clientWebSocket);
        }
        private TcpClient GetTcpConnection(DanmakuServer danmakuServer)
        {
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect(danmakuServer.Server, danmakuServer.Port);
            return(tcpClient);
        }
Example #4
0
 /// <summary>
 /// Connect
 /// </summary>
 public void Connect()
 {
     new Thread(delegate()
     {
         PingReply pingReply = null;
         try
         {
             if (timeout > 0)
             {
                 pingReply = new Ping().Send("live.bilibili.com", timeout);
             }
             else
             {
                 pingReply = new Ping().Send("live.bilibili.com");
             }
         }
         catch (Exception)
         {
         }
         if (pingReply == null || pingReply.Status != IPStatus.Success)
         {
             ConnectionFailed?.Invoke("网络连接失败");
             return;
         }
         DanmakuServer danmakuServer = GetDanmakuServer(roomId);
         if (danmakuServer == null)
         {
             return;
         }
         tcpClient = Connect(danmakuServer);
         StartEventListener(tcpClient);
         StartHeartbeatSender(tcpClient);
         Connected?.Invoke();
     }).Start();
 }
Example #5
0
        private DanmakuServer GetDanmakuServer(long roomId)
        {
            roomId = GetRealRoomId(roomId);
            if (roomId < 0)
            {
                return(null);
            }
            try
            {
                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create("https://api.live.bilibili.com/room/v1/Danmu/getConf?room_id=" + roomId);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Json.Value      json     = Json.Parser.Parse(response.GetResponseStream());
                if (json["code"] != 0)
                {
                    Console.Error.WriteLine("Error occurs when resolving dm servers");
                    Console.Error.WriteLine(json.ToString());
                    return(null);
                }

                DanmakuServer danmakuServer = new DanmakuServer();
                danmakuServer.RoomId  = roomId;
                danmakuServer.Server  = json["data"]["host_server_list"][0]["host"];
                danmakuServer.Port    = json["data"]["host_server_list"][0]["port"];
                danmakuServer.WsPort  = json["data"]["host_server_list"][0]["ws_port"];
                danmakuServer.WssPort = json["data"]["host_server_list"][0]["wss_port"];
                danmakuServer.Token   = json["data"]["token"];

                return(danmakuServer);
            }
            catch (WebException)
            {
                ConnectionFailed?.Invoke("直播间信息获取失败");
                return(null);
            }
        }
Example #6
0
        private TcpClient Connect(DanmakuServer danmakuServer)
        {
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect(danmakuServer.Server, danmakuServer.Port);
            NetworkStream networkStream = tcpClient.GetStream();

            //string msg = string.Format("{{\"roomid\":{0},\"uid\":{1}}}", danmakuServer,roomId, (long)(1e14 + 2e14 * new Random().NextDouble()));

            Json.Value initMsg = new Json.Value.Object();
            initMsg["uid"]       = 0;
            initMsg["roomid"]    = danmakuServer.RoomId;
            initMsg["protover"]  = 2;
            initMsg["platform"]  = "web";
            initMsg["clientver"] = "1.9.3";
            initMsg["type"]      = 2;
            initMsg["key"]       = danmakuServer.Token;

            try
            {
                BiliPackWriter.SendMessage(networkStream, (int)BiliPackWriter.MessageType.CONNECT, initMsg.ToString());
            }
            catch (SocketException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                Disconnect();
            }
            catch (InvalidOperationException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                Disconnect();
            }
            catch (IOException)
            {
                ConnectionFailed?.Invoke("连接请求发送失败");
                Disconnect();
            }
            return(tcpClient);
        }
        public bool Connect()
        {
            PingReply pingReply = null;

            try
            {
                pingReply = new Ping().Send("live.bilibili.com");
            }
            catch (Exception)
            {
            }
            if (pingReply == null || pingReply.Status != IPStatus.Success)
            {
                ConnectionFailed?.Invoke("网络连接失败");
                return(false);
            }

            DanmakuServer danmakuServer = GetDanmakuServer(RoomId);

            if (danmakuServer == null)
            {
                return(false);
            }

            switch (Protocol)
            {
            case Protocols.Tcp:
                DanmakuTcpClient = GetTcpConnection(danmakuServer);
                Stream stream = DanmakuTcpClient.GetStream();

                stream.ReadTimeout  = 30 * 1000 + 1000;
                stream.WriteTimeout = 30 * 1000 + 1000;

                PackReader = new BiliPackReader(stream);
                PackWriter = new BiliPackWriter(stream);
                break;

            case Protocols.Ws:
                DanmakuWebSocket = GetWsConnection(danmakuServer);
                PackReader       = new BiliPackReader(DanmakuWebSocket);
                PackWriter       = new BiliPackWriter(DanmakuWebSocket);
                break;

            case Protocols.Wss:
                DanmakuWebSocket = GetWssConnection(danmakuServer);
                PackReader       = new BiliPackReader(DanmakuWebSocket);
                PackWriter       = new BiliPackWriter(DanmakuWebSocket);
                break;
            }

            if (!InitConnection(danmakuServer))
            {
                Disconnect();
                return(false);
            }

            StartEventListener();
            StartHeartbeatSender();

            Connected?.Invoke();
            return(true);
        }