1.0.5 • Published 7 years ago

ws-srpc v1.0.5

Weekly downloads
1
License
MIT
Repository
-
Last release
7 years ago

ws-srpc: a Node.js WebSocket library

Version npm Linux Build Windows Build Coverage Status

ws-srpc extends from ws module. Added heartbeat mechanism、reconect、ack、simple RPC

Note: This module does not work in the browser.

Table of Contents

Installing

npm install --save ws-srpc

Usage examples

create server

const ws_server = require('ws-srpc').server;

var wss = new ws_server({ port: 8081,verifyfn:verifying_login,//配置服务端接入验证函数
                            seviceTodo:exec_service//配置逻辑处理函数
                        }) ;

wss.on('connection',function(ws){
    ws.sendWithReply({cmd: 'info'}, function (err, msg) {
        if (err) return console.log('reply error-->', err);
        console.log('send \{cmd: \'info\'\}  client reply-->', msg);
    });
})
/**
 * connection verify funtion
 * must retun true or false;
 * @param req
 * @returns {*}
 */
function verifying_login(req){
    if(!req || !req.headers ||!req.headers['connect_sign']) return false;
    return true;
}
/**
 * service logic
 * @param msg {'cmd':xxx}
 * @returns {*}
 */

async function exec_service(msg){
    console.log('exec_service, receive client msg-->',msg);
    switch (msg.cmd){
        case 'info':
            return 'I ma ws server!';
        default:
            console.log('recv undefine cmd');
            return 'undefine cmd';
    }
}```

### create client

```js
const wsclient = require('ws-srpc').client;

let ws = new wsclient('ws://localhost:8081', {isReconnect: true,
    seviceTodo: exec_service,//配置逻辑处理函数
    headers:{connect_sign:'connection verify'}//配置验证信息
});

ws.on('open', function () {
    console.log('isOpen-->', ws.isConnect());

    ws.sendWithReply({cmd: 'info'}, function (err, msg) {
        if (err) return console.log('reply error-->', err);

        console.log('server reply-->', msg);
    });

});

async function exec_service(msg) {
    console.log('receive server msg-->',msg);
    switch (msg.cmd) {
        case 'info':
            return 'I am ws client';
        default:
            console.log('receive server undefine cmd');
            return 'undefine cmd';
    }
}

##ws function sendmsg:send message with ack sendWithReply:send message and wait reply _sendmsg:send message getRemoteAddress: get remote IP address isConnect: return client state

##server function broadcast: broadcast message to all connected client

License

MIT

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago