网页版陌陌直播弹幕协议抓取和发送
基于 websocket协议
具体分析过程就不说了 大家自己F12抓包分析下一目了然 没有什么难度
我直接上源码例程
socket协议连接
弹幕抓取
弹幕发送
心跳包
各个地方我都备注了
代码块
static ClientWebSocket _webSocket = new ClientWebSocket();
async static Task Main(string[] args)
{
_webSocket = new ClientWebSocket();
Connect();
Console.ReadLine();
}
/// <summary>
/// WebSocket客户端连接
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static async Task Connect()
{
CancellationTokenSource t = new CancellationTokenSource();
try
{
Uri uri = new Uri("wss://live-ws.immomo.com/ws/im");
//var config=new ServerConfig
await _webSocket.ConnectAsync(uri, t.Token);
Thread.Sleep(300);
Console.WriteLine($"链接websocket:[{uri}] 完成");
Task s1 = new Task(Receive, t, t.Token, TaskCreationOptions.LongRunning);
s1.Start();
var client_time = "1666113617240";//时间戳 毫秒级
var momoid = "256654841";//自己的陌陌ID
var roomid = "1476810196216";//直播间ID
var token = "236a4f4899725a8e63dc70babfacb936";//登陆凭证 登陆完成在 cookie的 live_web_session_im
var data = "{\"msg_id\":1,\"client_time\":" + client_time + ",\"type\":\"Sauth\",\"data\":{\"momoid\":\"" + 256654841 + "\",\"roomid\":\"" + roomid + "\",\"role\":6,\"isVisitor\":false,\"token\":\"" + token + "\",\"ua\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36\"}}";
var bs = Encoding.Default.GetBytes(data);
await _webSocket.SendAsync(new ArraySegment<byte>(bs), WebSocketMessageType.Text, true, CancellationToken.None);
//{"msg_id":3,"client_time":1666196718270,"type":"Ping","data":{}} 心跳包内容
//{"msg_id":2,"client_time":1666196713852,"type":"Bili","data":{"text":"6666666666666666666666666666666666666"}} 发送弹幕包 内容
Console.WriteLine("Send Hello");
}
catch (Exception ex)
{
Console.WriteLine($"链接websocket:[] 失败", ex.Message);
}
}
private static void Receive(object obj)
{
CancellationTokenSource ts = obj as CancellationTokenSource;
byte[] bs = new byte[1024];
while (!ts.Token.IsCancellationRequested)
{
try
{
ArraySegment<byte> buff = new ArraySegment<byte>(bs, 0, bs.Length);
Task<WebSocketReceiveResult> res = _webSocket.ReceiveAsync(buff, ts.Token);
if (ts.Token.IsCancellationRequested)
{
return;
}
if (WebSocketCloseStatus.NormalClosure == res.Result.CloseStatus)
{
Console.WriteLine($"websocket:与服务器断开链接:{res.Result.CloseStatus} --> Desc :{res.Result.CloseStatusDescription}");
ts.Cancel();
return;
}
string strData = Encoding.UTF8.GetString(bs, 0, res.Result.Count);
Console.WriteLine("收到消息=>" + strData);
}
catch (Exception ex)
{
Console.WriteLine("解析或执行 websocket:命令失败", ex);
}
}
}
image.png
代码一目了然 大家可以自己试试
如果不是用c# 大家用自己会的语言实现即可 代码格式基本都差不多
网友评论