// 导入WebSocket模块:
const WebSocket = require(‘ws‘);
// 引用Server类:
const WebSocketServer = WebSocket.Server;
// 实例化:
const wss = new WebSocketServer({
port: 3001
});
wss.on(‘connection‘, function (ws) {
console.log(`ws 已经连接上`);
ws.on(‘message‘, function (message) {
console.log(`收到客户端的数据: ${message}`);
ws.send(`服务端接收到数据,给客户端返回数据: ${message}`, (err) => {
if (err) {
console.log(`[SERVER] error: ${err}`);
}
});
})
});
2. html代码
// 打开一个WebSocket:
var ws = new WebSocket(‘ws://localhost:3001‘);
// 响应onmessage事件:
ws.onmessage = function (msg) { console.log(msg); };
// 给服务器发送一个字符串:
ws.addEventListener(‘open‘, function () {
let msg = ‘我是客户端: ‘ + location.href
ws.send(msg)
});
3. 当然 必须提前导入ws模块 npm i ws