Skip to content

synquery/node-websockets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

node-websockets

Web Socket Server and Client API
Support Protocols

Install

npm i https://github.com/synquery/node-websockets.git

Usage

require websockets

const websockets = require("websockets");

Server:

Server is a wrapper of http/https server.

// http based server
const server = websockets.createServer();
server.on('connect', function(socket) {
  socket.on('message', function(message) {
    socket.send('echo a message:' + message);
    ......
  });
}).listen(80);

// https based server
const secure = 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'
const express = require('express');

const rest_svr = express.createServer();
rest_svr.get('/', function(req, res) {
  ......
});
svr.configure(function() {
  ......
});

const server = websockets.createServer({
  server: rest_svr
});
server.on('connect', function(socket) {
  socket.on('message', function(message) {
    socket.send('echo a message:' + message);
    ......
  });
}).listen(80);

Client:

Client has the interfaces like html5 WebSocket.

const socket = new websockets.WebSocket('wss://127.0.0.1');
or
const socket = new websockets.connect('wss://127.0.0.1');
socket.on('open', function() {
  socket.send('a message');
  ......
});
socket.on('message', ...)

APIs

websockets.Server


Event: 'connect'

function (socket) {}

Emitted when client-server opening handshake has succeeded. socket is an instance of WebSocket.


server.broadcast(string, site)

Sends string to all clients connected with server. if site sets "true", then, sends to clients access from same pathname.


server.broadcast(buffer)

Not Implemented. Sends binary data(buffer) to all clients connected with server.


websockets.WebSocket


Event: 'open'

function () {}

Emitted when a client-server connection is successfully established.


Event: 'message'

function (data) {}

Emitted when the socket has received a message. The type of data is either string(string data) or Buffer(binary data).


Event: 'error'

function (exception) {}

Emitted on error. exception is an instance of Error.


Event: 'close'

function () {}

Emitted when a client-server connection has closed.


socket.send(string)

Sends string to the other endpoint.


socket.send(buffer)

Sends binary data(buffer) to the other endpoint.


socket.close()

Sends a connection close request to the other endpoint.


TODO = * test of sending on binary mode.

About

WebSocket Server & Client API

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published