From 47955fd4248f343e21a074edddf60c358c40d45c Mon Sep 17 00:00:00 2001 From: kooritea Date: Wed, 3 Jul 2019 19:09:56 +0800 Subject: [PATCH] fix websocket in browser --- API.WebSocket.md | 109 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 84 insertions(+), 25 deletions(-) diff --git a/API.WebSocket.md b/API.WebSocket.md index 1d47881..1627395 100644 --- a/API.WebSocket.md +++ b/API.WebSocket.md @@ -70,20 +70,81 @@ Bilibili 直播弹幕 WebSocket 协议 这里以浏览器 JavaScript 自带的 `WebSocket` 说明 -1. 连接 WebSocket - +1. 声明encode和decode方法 ```javascript -const ws = new WebSocket('wss://broadcastlv.chat.bilibili.com:2245/sub'); +const textEncoder = new TextEncoder('utf-8'); +const textDecoder = new TextDecoder('utf-8'); + +const readInt = function(buffer,start,len){ + let result = 0 + for(let i=len - 1;i >= 0;i--){ + result += Math.pow(256,len - i - 1) * buffer[start + i] + } + return result +} + +const writeInt = function(buffer,start,len,value){ + let i=0 + while(i{ switch (body.cmd) { case 'DANMU_MSG': console.log(`${body.info[2][1]}: ${body.info[1]}`); @@ -127,10 +186,10 @@ ws.on('message', function (data) { default: console.log(body); } - break; - default: - console.log(packet); - } + }) + break; + default: + console.log(packet); } -}); +}; ```