1.安装node。https://nodejs.org/en/
2.安装ws模块
ws:是nodejs的一个WebSocket库,可以用来创建服务。 https://github.com/websockets/ws
3.创建一个Server
代码语言:javascript复制var fs = require('fs')
const WebSocket = require('ws');
var fs = require('fs');
function CreateWebSocketServer(host, port)
{
var server = new WebSocket.Server({ port: port, host:host} );
server.on('connection', function connection(client, req) {
client.on('message', function incoming(message) {
//cb.OnRequest(client, message);
client.send("rsp:" new Date(), null, (error)=>{
console.log("send error:" error)
})
});
client.on('close', function (errno, message) {
console.log("closed:" errno " " message)
});
client.on('error', function(err){
console.log("error:" err);
} )
});
}
CreateWebSocketServer("localhost", 8080)
4.node server.js运行服务;