由于本博主在搞云直播游戏,所以一直在研究java直播弹幕获取
弹幕协议用的是websocket
流程就是:1.连接websocket 2.发送直播间数据和token 3.就能获取到弹幕的推送
以下就是关键代码,懂得自然懂!只要稍微研究一下弹幕 就能看懂我写的啥
源码
@Override public void onOpen(ServerHandshake arg0) { // TODO Auto-generated method stub LOGGER.info("------ MyWebSocket onOpen ------"); //==开头 //byte[] part1=hexToBytes("08c8011ac8010a9801"); //=开头 byte[] part1 = hexToBytes("08c8011adc010aac01"); if (token.lastIndexOf("==") > 0) { part1 = hexToBytes("08c8011ac8010a9801"); } //token byte[] part2 = token.getBytes(); //固定 byte[] part3 = hexToBytes("120b"); //stream_id byte[] part4 = streamId.getBytes(); //固定 byte[] part5 = hexToBytes("3a1e"); //page_id byte[] part6 = getPageId().getBytes(); List<byte[]> datas = new LinkedList<>(Arrays.asList(part1, part2, part3, part4, part5, part6)); byte[] resultBytes = new byte[0]; //记录需要复制到目标数组的起始索引 int index = 0; for (byte[] bytes : datas) { //复制数组到新数组,并且长度为当前数组长度+bytes的长度 resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + bytes.length); //将bytes中的内容拼接在结果数组之后 System.arraycopy(bytes, 0, resultBytes, index, bytes.length); //索引值递增 index += bytes.length; } send(resultBytes); TimerTask task = new TimerTask() { public void run() { //20秒心跳包 // String data = byte2Hex(HttpClientUtils.executeByPOST("https://live.kuaishou.com/rest/wd/live/watchingFeed","{\"liveStreamId\":\""+streamId+"\"}").getBytes()); // System.out.println(data); byte[] heartBeat = hexToBytes("08011a070889aac0da8130"); LOGGER.info("******心跳******"); send(heartBeat); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 20 * 1000; timer.scheduleAtFixedRate(task, delay, intevalPeriod); }
效果
本文为程序员之家原创文章,转载无需和我联系,但请注明来自程序员之家www.baldhome.com