This commit is contained in:
abearxiong committed 2025-05-06 22:16:31 +08:00
commit 54f5caeeaa
33 files changed
+7191

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["johnsoncodehk.volar"]
}
+5
View File
@@ -0,0 +1,5 @@
### DEMO
此处为验证API的调试环境
By Vite
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+2694
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "poros-demo-client",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite --port 8888 --host 0.0.0.0 ",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.2.25"
},
"devDependencies": {
"@originjs/vite-plugin-commonjs": "1.0.3",
"@types/node": "17.0.25",
"@vitejs/plugin-vue": "2.3.0",
"axios": "0.26.1",
"typescript": "4.5.4",
"vite": "2.9.0",
"vue-tsc": "0.29.8"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

+196
View File
@@ -0,0 +1,196 @@
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import { ref } from "vue"
import axios from "axios"
import { createSocket, destroySocket } from "./socket/index"
const api = axios.create({
baseURL: "http://localhost:3000",
})
// 替换你的秘钥
const appKey = ref("")
const appSecret = ref("")
// 替换你的主播身份码
const codeId = ref("")
// 替换你的app应用 [这里测试为互动游戏]
const appId = ref("")
// [向 node server请求接口后自动返回]
const gameId = ref("")
// v2改为server response 服务器返回websocket信息,而非手动获取
const authBody = ref("")
const wssLinks = ref([])
// heartBeat Timer
const heartBeatTimer = ref<NodeJS.Timer>()
// be ready
clearInterval(heartBeatTimer.value!)
/**
* 测试请求鉴权接口
*/
const getAuth = () => {
api.post("/getAuth", {
appKey: appKey.value,
appSecret: appSecret.value,
})
.then(({ data }) => {
console.log("-----鉴权成功-----")
console.log("返回:", data)
})
.catch((err) => {
console.log("-----鉴权失败-----")
})
}
const heartBeatThis = (game_id) => {
// 心跳 是否成功
api.post("/gameHeartBeat", {
game_id,
})
.then(({ data }) => {
console.log("-----心跳成功-----")
console.log("返回:", data)
})
.catch((err) => {
console.log("-----心跳失败-----")
})
}
/**
* @comment 注意所有的接口基于鉴权成功后才能正确返回
* 测试请求游戏开启接口
*/
const gameStart = () => {
api.post("/gameStart", {
code: codeId.value,
app_id: Number(appId.value),
})
.then(({ data }) => {
if (data.code === 0) {
const res = data.data
const { game_info, websocket_info } = res
const { auth_body, wss_link } = websocket_info
authBody.value = auth_body
wssLinks.value = wss_link
console.log("-----游戏开始成功-----")
console.log("返回GameId:", game_info)
gameId.value = game_info.game_id
// v2改为20s请求心跳一次,不然60s会自动关闭
heartBeatTimer.value = setInterval(() => {
heartBeatThis(game_info.game_id)
}, 20000)
} else {
console.log("-----游戏开始失败-----")
console.log("原因:", data)
}
})
.catch((err) => {
console.log("-----游戏开始失败-----")
console.log(err)
})
}
/**
* @comment 基于gameStart成功后才会关闭正常,否则获取不到game_id
* 测试请求游戏关闭接口
*/
const gameEnd = () => {
api.post("/gameEnd", {
game_id: gameId.value,
app_id: Number(appId.value),
})
.then(({ data }) => {
if (data.code === 0) {
console.log("-----游戏关闭成功-----")
console.log("返回:", data)
// 清空长链
authBody.value = ""
wssLinks.value = []
clearInterval(heartBeatTimer.value)
handleDestroySocket()
console.log("-----心跳关闭成功-----")
} else {
console.log("-----游戏关闭失败-----")
console.log("原因:", data)
}
})
.catch((err) => {
console.log("-----游戏关闭失败-----")
console.log(err)
})
}
/**
* 测试创建长长连接接口
*/
const handleCreateSocket = () => {
if (authBody.value && wssLinks.value) {
createSocket(authBody.value, wssLinks.value)
}
}
/**
* 测试销毁长长连接接口
*/
const handleDestroySocket = () => {
destroySocket()
console.log("-----长连接销毁成功-----")
}
</script>
<template>
<div>
<h3>-- !-- 所有输出信息都在控制台 -- --</h3>
<div>鉴权部分</div>
<div class="form">
<input
type="text"
placeholder="填写access_key_id"
v-model="appKey"
/>
<input
type="text"
placeholder="填写access_key_secret"
v-model="appSecret"
/>
<button @click="getAuth">鉴权</button>
</div>
<hr />
<div>程序开启部分 [需要先鉴权]</div>
<div class="form">
<input type="text" placeholder="填写主播身份码" v-model="codeId" />
<input type="text" placeholder="填写 app_id" v-model="appId" />
<button @click="gameStart">游戏开始</button>
<button @click="gameEnd">游戏结束</button>
</div>
<hr />
<div>长连接部分 [需要先游戏开启]</div>
<div class="form">
<button @click="handleCreateSocket">建立长连接</button>
<button @click="handleDestroySocket">销毁长连接</button>
</div>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.form {
display: flex;
flex-direction: column;
}
.form input,
.form button {
width: 400px;
height: 50px;
margin: 10px 0;
}
</style>
+8
View File
@@ -0,0 +1,8 @@
/*!
* Bilibili Player Danmaku Websocket Component v1.4.3 (32)
*
* Copyright 2016 - 2020 Bilibili, Inc.
* Released in Fri Nov 27 2020 15:45:21 GMT+0800 (China Standard Time)
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.DanmakuWebSocket=t():e.DanmakuWebSocket=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var o=n[i]={i:i,l:!1,exports:{}};return e[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,i){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:i})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=1)}([function(e,t,n){"use strict";var i={WS_OP_HEARTBEAT:2,WS_OP_HEARTBEAT_REPLY:3,WS_OP_MESSAGE:5,WS_OP_USER_AUTHENTICATION:7,WS_OP_CONNECT_SUCCESS:8,WS_PACKAGE_HEADER_TOTAL_LENGTH:16,WS_PACKAGE_OFFSET:0,WS_HEADER_OFFSET:4,WS_VERSION_OFFSET:6,WS_OPERATION_OFFSET:8,WS_SEQUENCE_OFFSET:12,WS_BODY_PROTOCOL_VERSION_NORMAL:0,WS_BODY_PROTOCOL_VERSION_DEFLATE:2,WS_HEADER_DEFAULT_VERSION:1,WS_HEADER_DEFAULT_OPERATION:1,WS_HEADER_DEFAULT_SEQUENCE:1,WS_AUTH_OK:0,WS_AUTH_TOKEN_ERROR:-101};t.a=i},function(e,t,n){var i=n(2).default;e.exports=i},function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=n(3),r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),a=function(){function e(t){return i(this,e),"development"===e.CONFIG.bundleType&&(console.clear(),console.dir(e.CONFIG)),this.initialize(t)}return e.prototype.initialize=function(t){return"development"===e.CONFIG.bundleType&&console.log("App Initialized."),this.ws=new o.a(t),this.getReturn()},e.prototype.getReturn=function(){return"development"===e.CONFIG.bundleType?this:{destroy:this.destroy.bind(this),send:this.send.bind(this),getAuthInfo:this.getAuthInfo.bind(this),getRetryCount:this.getRetryCount.bind(this)}},e.prototype.destroy=function(){this.ws&&this.ws.destroy()},e.prototype.send=function(e){this.ws&&this.ws.send(e)},e.prototype.getAuthInfo=function(){return this.ws&&this.ws.getAuthInfo()},e.prototype.getRetryCount=function(){return this.ws&&this.ws.getRetryCount()},r(e,null,[{key:"CONFIG",get:function(){return{version:"1.4.3",gitHash:"bf68b6a8",build:"32",bundleType:"release"}}}]),e}();t.default=a},function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(0),r=n(4),a=n(5),s=n(6).inflate,u=function(){function e(t){if(i(this,e),e.checkOptions(t)){var n={url:"",urlList:[],rid:0,aid:0,uid:0,from:-1,retry:!0,retryMaxCount:0,retryInterval:5,retryThreadCount:10,connectTimeout:5e3,retryConnectCount:3,retryconnectTimeout:1e4,retryRoundInterval:Math.floor(2*Math.random())+3,customAuthParam:[],fallback:function(){},heartBeatInterval:30,onReceivedMessage:function(){},onReceiveAuthRes:function(){},onHeartBeatReply:function(){},onInitialized:function(){},onOpen:function(){},onClose:function(){},onError:function(){},onListConnectError:function(){}};this.options=a.a.extend({},n,t),this.wsBinaryHeaderList=a.a.extend([],r.a),this.authInfo={origin:"",encode:""},0!==this.options.urlList.length&&0!==this.options.retryMaxCount&&this.options.retryMaxCount<this.options.urlList.length&&(this.options.retryMaxCount=this.options.urlList.length-1),this.state={retryCount:0,listConnectFinishedCount:0,index:0,connectTimeoutTimes:0},this.callbackQueueList={onInitializedQueue:[],onOpenQueue:[],onCloseQueue:[],onErrorQueue:[],onReceivedMessageQueue:[],onHeartBeatReplyQueue:[],onRetryFallbackQueue:[],onListConnectErrorQueue:[],onReceiveAuthResQueue:[]},this.HEART_BEAT_INTERVAL=0,this.CONNECT_TIMEOUT=0,this.mixinCallback().initialize(this.options.urlList.length>0?this.options.urlList[0]:this.options.url)}}return e.prototype.initialize=function(e){var t=this,n="MozWebSocket"in window?window.MozWebSocket:window.WebSocket,i=this.options;try{this.ws=new n(e),this.ws.binaryType="arraybuffer",this.ws.onopen=this.onOpen.bind(this),this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this),this.ws.onerror=this.onError.bind(this),a.a.callFunction(this.callbackQueueList.onInitializedQueue),this.callbackQueueList.onInitializedQueue=[];var o=this.state.connectTimeoutTimes>=3?i.retryconnectTimeout:i.connectTimeout;this.CONNECT_TIMEOUT=setTimeout(function(){t.state.connectTimeoutTimes+=1,console.error("connect timeout ",t.state.connectTimeoutTimes),t.ws.close()},o)}catch(e){"function"==typeof i.fallback&&i.fallback()}return this},e.prototype.onOpen=function(){return a.a.callFunction(this.callbackQueueList.onOpenQueue),this.state.connectTimeoutTimes=0,this.CONNECT_TIMEOUT&&clearTimeout(this.Line truncated
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}
+5
View File
@@ -0,0 +1,5 @@
import { createApp } from "vue"
import App from "./App.vue"
createApp(App).mount("#app")
+80
View File
@@ -0,0 +1,80 @@
import DanmakuWebSocket from "../assets/danmaku-websocket.min.js"
let ws: DanmakuWebSocket
/**
* 创建socket长连接
* @param authBody
* @param wssLinks
*/
function createSocket(authBody: string, wssLinks: string[]) {
const opt = {
...getWebSocketConfig(authBody, wssLinks),
// 收到消息,
onReceivedMessage: (res) => {
console.log(res)
},
// 收到心跳处理回调
onHeartBeatReply: (data) => console.log("收到心跳处理回调:", data),
onError: (data) => console.log("error", data),
onListConnectError: () => {
console.log("list connect error")
destroySocket()
},
}
if (!ws) {
ws = new DanmakuWebSocket(opt)
}
return ws
}
/**
* 获取websocket配置信息
* @param authBody
* @param wssLinks
*/
function getWebSocketConfig(authBody: string, wssLinks: string[]) {
const url = wssLinks[0]
const urlList = wssLinks
const auth_body = JSON.parse(authBody)
return {
url,
urlList,
customAuthParam: [
{
key: "key",
value: auth_body.key,
type: "string",
},
{
key: "group",
value: auth_body.group,
type: "string",
},
],
rid: auth_body.roomid,
protover: auth_body.protoover,
uid: auth_body.uid,
}
}
/**
* 销毁websocket
*/
function destroySocket() {
console.log("destroy1")
ws && ws.destroy()
ws = undefined
console.log("destroy2")
}
/**
* 获取websocket实例
*/
function getWsClient() {
return ws
}
export { createSocket, destroySocket, getWebSocketConfig, getWsClient }
+19
View File
@@ -0,0 +1,19 @@
declare interface ISocketData {
// ip地址
ip: number[]
// host地址 可能是ip 也可能是域名。
host: string[]
// 长连使用的请求json体 第三方无需关注内容,建立长连时使用即可。
auth_body: string
// tcp 端口号
tcp_port: number[]
// ws 端口号
ws_port: number[]
// wss 端口号
wss_port: number[]
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es2016",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"types": ["node"],
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+8
View File
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "node"
},
"include": ["vite.config.ts"]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import { viteCommonjs } from "@originjs/vite-plugin-commonjs"
import * as path from "path"
// https://vitejs.dev/config/
export default defineConfig({
server: {
// https: true
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src")
}
},
plugins: [vue(), viteCommonjs()]
})