依赖模块
nodejs-websocket
服务端
const ws = require(‘nodejs-websocket‘);
console.log(‘开始建立连接...‘);
const server = ws.createServer(function(conn) {
conn.on(‘text‘, function(str) {
console.log(‘收到的信息为:‘ + str);
conn.send(str);
});
conn.on(‘close‘, function(code, reason) {
console.log(‘关闭连接‘);
});
conn.on(‘error‘, function(code, reason) {
console.log(‘异常关闭‘);
});
}).listen(8001);
console.log(‘WebSocket建立完毕‘);
客户端
var ws = new WebSocket(‘ws://localhost:8001‘);
ws.onopen = function() {
console.log(‘open‘);
ws.send(‘hello‘);
};
ws.onmessage = function(evt) {
console.log(‘message:‘, evt.data)
};
ws.onclose = function(evt) {
console.log(‘close‘);
};
时间: 2024-10-04 20:38:24