1
0
Code Issues Pull Requests Packages Projects Releases Wiki Activity GitHub Gitee

[后端] webSocket demo跑通

This commit is contained in:
2022-11-28 23:29:03 +08:00
parent a85d7bcfba
commit 432ba2b812
11 changed files with 382 additions and 2 deletions

1
test-code/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
node_modules

44
test-code/package-lock.json generated Normal file
View File

@@ -0,0 +1,44 @@
{
"name": "test-code",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "test-code",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"ws": "^8.11.0"
}
},
"node_modules/ws": {
"version": "8.11.0",
"resolved": "https://registry.npmmirror.com/ws/-/ws-8.11.0.tgz",
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
},
"dependencies": {
"ws": {
"version": "8.11.0",
"resolved": "https://registry.npmmirror.com/ws/-/ws-8.11.0.tgz",
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
"requires": {}
}
}
}

14
test-code/package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "test-code",
"version": "1.0.0",
"description": "",
"main": "websocketTest.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ws": "^8.11.0"
}
}

View File

@@ -0,0 +1,45 @@
'use strict';
const WebSocket = require('ws');
const webSocketUrl = 'ws://localhost:8002/websocket/1';
global.ws = null; // WebSocket 实例对象
/**
* 启动完毕,输出配置信息
*/
console.log("Start running ...", "process.env", process.env);
function createWebSocket() {
//申请一个WebSocket对象参数是服务端地址同http协议使用http://开头一样WebSocket协议的url使用ws://开头另外安全的WebSocket协议使用wss://开头
global.ws = new WebSocket(webSocketUrl);
// 当WebSocket创建成功时触发onopen事件
global.ws.onopen = function () {
console.log("webhook is open.");
}
// 当客户端收到服务端发送的关闭连接请求时触发onclose事件
global.ws.onclose = function (e) {
console.log("webhook is close.");
console.log("未知错误被关闭,等待 1s 尝试重新建立连接...");
setTimeout(function () {
createWebSocket();
}, 1000);
}
// 如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
global.ws.onerror = function (e) {
console.log(e.error);
}
// 当客户端收到服务端发来的消息时触发onmessage事件参数e.data包含server传递过来的数据
global.ws.onmessage = function (e) {
var data = JSON.parse(e.data);
console.log(data);
}
}
// 创建连接
createWebSocket();