46 lines
1.4 KiB
JavaScript
46 lines
1.4 KiB
JavaScript
|
'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();
|