C#获取虎牙直播弹幕

C#获取虎牙直播弹幕

连接websocket接口并监听弹幕消息事件获取直播间的弹幕信息

注册虎牙开放平台

注册并通过实名认证去获取生成JWT token 的appId、appSecret参数。点击查看

  • 开放平台地址
  • 文档

安装nuget包

Install-Package WebSocketSharp-netstandard
Install-Package Newtonsoft.Json
Install-Package Microsoft.IdentityModel.Tokens
Install-Package System.IdentityModel.Tokens.Jwt

C#代码

using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using WebSocketSharp;

namespace Danmu
{
    class Program
    {
        static void Main(string[] args)
        {

            string appId = "";
            string appSecret = "";
            string wss = "wss://ws-apiext.huya.com/index.html?do=comm&roomId={0}&appId={1}&iat={2}&exp={3}&sToken={4}";

            // 房间Id
            long roomId = 52988;

            long iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            string token = GetToken(appId, appSecret, iat);
            string url = string.Format(wss, roomId, appId, iat, iat + 60 * 50, token);

            WebSocket ws = new WebSocket(url);
            // 
            ws.OnOpen += (sender, e) =>
            {
                string reqId = $"DM_{DateTime.Now:yyyyMMddHHmmssffffff}";
                // 订阅弹幕
                string sendMsg = "{\"command\":\"subscribeNotice\",\"data\":[\"getMessageNotice\"],\"reqId\":\"" + reqId + "\"}";
                ws.Send(sendMsg);
            };
            ws.OnMessage += (object sender, MessageEventArgs e) =>
            {
                Console.WriteLine(e.Data);
            };
            ws.OnClose += (sender, e) =>
            {
                // 关闭
            };
            ws.OnError += (sender, e) =>
            {
                // 异常
            };
            ws.Connect();
            Console.ReadKey();
        }

        private static string GetToken(string appId, string scurityKey, long iat)
        {
            // 生成 JWT 的头部
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(scurityKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var header = new JwtHeader(signingCredentials);

            // 生成 JWT 的负载
            var payload = new JwtPayload();
            payload.Add("iat", iat);
            payload.Add("exp", iat + 50 * 60);
            payload.Add("appId", appId);

            // 使用密钥对 JWT 进行签名
            var token = new JwtSecurityToken(
                header,
                payload
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}

你可能感兴趣的:(WebSocket,C#,c#,开发语言,虎牙直播间弹幕)