Skip to content

Instantly share code, notes, and snippets.

@miaozilong
Created January 23, 2021 17:47
Show Gist options
  • Save miaozilong/6c9d89030a6ec4a2c148799c43de5688 to your computer and use it in GitHub Desktop.
Save miaozilong/6c9d89030a6ec4a2c148799c43de5688 to your computer and use it in GitHub Desktop.
websocket to http
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// 事件对象
let eventObj = {};
let pubsub = {
sub: (key, fn) => {
eventObj[key] = fn
},
pub: (key) => {
if (eventObj[key]) {
eventObj[key]()
}
}
}
// 超时时间
const timeoutInterval = 30 * 1000;
let errorMap = {
parameterError: {
code: 501,
message: '参数不正确'
},
timeout: {
code: 502,
message: '请求超时'
},
netException: {
code: 503,
message: '断网异常'
}
}
let wsRequest = (option) => new Promise((resolve, reject) => {
if (!option.context) {
reject(errorMap.parameterError)
}
setTimeout(() => {
reject(errorMap.timeout)
delete eventObj[option.context];
}, timeoutInterval)
pubsub.sub(option.context, (data) => {
resolve(data)
delete eventObj[option.context];
})
pubsub.sub('disconnect', () => {
reject(errorMap.netException)
})
})
let ws = new WebSocket('ws://127.0.0.1:4649/Echo?name=pengbo');
// ws.onopen = (e) => {
// }
let onCloseOrError = () => {
eventObj = {}
pubsub.pub('disconnect')
};
ws.onclose = onCloseOrError
ws.onerror = onCloseOrError
ws.onmessage = (rsp) => {
let data = JSON.parse(rsp.data);
if (data.msgType === 'rsp') {
eventObj[data.context] && eventObj[data.context](data);
}
}
(async function () {
// 测试发送ws请求
try {
let rsp = await Promise.all([
wsRequest({
context: '123',
msgType: 'req',
data: 'data123'
})
,
wsRequest({
context: '124',
msgType: 'req',
data: 'data124'
})
])
console.log(rsp)
debugger
} catch (e) {
console.log(e)
} finally {
}
})()
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment