代码如下, var WebSocketServer = require(‘ws’).Server; var express = require(‘express’); var app = express.createServer();
var globalServerPort = 8888;
// 开启websocket服务,让客户端连接进入房间 var wsServer; try { wsServer= new WebSocketServer({server: app}); wsServer.on('connection’, function(ws) { // 提示 console.log(“a new connection ws :” + ws);
// 监听该连接打开
ws.onopen = function() {
console.log('connection is open ! ws is :' + ws);
};
// 监听该连接上的消息
ws.onmessage = function(event) {
// 打印
console.log(event.data);
};
// 监听该连接关闭
ws.onclose = function() {
console.log('connection is close ! ws is :' + ws);
};
});
app.listen(globalServerPort);
console.log('app 执行了listen ');
} catch (e) { console.log(‘catch an exception!’); } finally { console.log(‘finally !’); }
执行结果如下: E:>node test.js app ִ����listen finally !
node.js:201 throw e; // process.nextTick error, or ‘error’ event on first tick ^ Error: listen EADDRINUSE at errnoException (net.js:642:11) at Array.0 (net.js:743:26) at EventEmitter._tickCallback (node.js:192:40)
E:>
6 回复