npm i https://github.com/synquery/node-websockets.git
require websockets
constwebsockets=require("websockets");Server is a wrapper of http/https server.
// http based serverconstserver=websockets.createServer();server.on('connect',function(socket){socket.on('message',function(message){socket.send('echo a message:'+message);
......
});}).listen(80);// https based serverconstsecure=websockets.createServer({key: ssl_key,cert: ssl_cert});secure.on('connect',function(socket){
......
}).listen(443);Extended Servers such as express are also available.
// In case of 'express'constexpress=require('express');constrest_svr=express.createServer();rest_svr.get('/',function(req,res){
......
});svr.configure(function(){
......
});constserver=websockets.createServer({server: rest_svr});server.on('connect',function(socket){socket.on('message',function(message){socket.send('echo a message:'+message);
......
});}).listen(80);Client has the interfaces like html5 WebSocket.
constsocket=newwebsockets.WebSocket('wss://127.0.0.1');orconstsocket=newwebsockets.connect('wss://127.0.0.1');socket.on('open',function(){socket.send('a message');
......
});socket.on('message', ...)function (socket) {}
Emitted when client-server opening handshake has succeeded. socket is an instance of WebSocket.
Sends string to all clients connected with server.
if site sets "true", then, sends to clients access from same pathname.
Not Implemented.
Sends binary data(buffer) to all clients connected with server.
function () {}
Emitted when a client-server connection is successfully established.
function (data) {}
Emitted when the socket has received a message. The type of data is either string(string data) or Buffer(binary data).
function (exception) {}
Emitted on error. exception is an instance of Error.
function () {}
Emitted when a client-server connection has closed.
Sends string to the other endpoint.
Sends binary data(buffer) to the other endpoint.
Sends a connection close request to the other endpoint.
TODO = * test of sending on binary mode.