websocket programming base on nodejs

网络程序设计无疑是nodejs + html最好用

一、nodejs的安装

1、在ubuntu上的安装

 sudo apt install nodejs-legacy

 sudo apt install npm

node.js 升级与版本切换——最简单的方法

https://segmentfault.com/a/1190000006869650

 

2、从nodejs v4版本开始已经发布了适用于嵌入式的运行环境,

我的硬件平台是cortex a5, armv7体系结构的,用最新版node-v9.9.0-linux-armv7l.tar.gz

官网https://nodejs.org/download/release

文档手册https://nodejs.org/api/

中文社区https://cnodejs.org/

 

3、在ARM核上的安装

1)解压安装文件
cp node-v9.9.0-linux-armv7l.tar.gz /usr/local/
cd /usr/local/
tar xvf node-v9.9.0-linux-armv7l.tar.gz

2)添加环境变量
PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/node-v9.9.0-linux-armv7l/bin"
export LD_LIBRARY_PATH=/usr/local/node-v9.9.0-linux-armv7l/lib:$LD_LIBRARY_PATH

3)测试实例 http_server_test.js
var http = require("http");
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);
console.log("nodejs start listen 8888 port!");

 

4、也可以自己编译源码

export CC=arm-linux-gnueabihf-gcc
export CXX=arm-linux-gnueabihf-g++
export LD=arm-linux-gnueabihf-ld
export RAINLIB=arm-linux-gnueabihf-rainlib
export AR=arm-linux-gnueabihf-ar

export LINK=arm-linux-gnueabihf-g++
./configure --prefix=/home/dong/armnodejs --dest-cpu=arm --dest-os=linux --cross-compiling --fully-static --with-arm-float-abi=hard --without-snapshot

make
make install

 

二、nodejs实现websocket应用

1、nodejs实现websocket的应用程序, 无论是服务端还是客户端都非常容易。

 1)有WebSocket-Node这个开源库就够用了

https://github.com/theturtle32/WebSocket-Node

另外下面这个也很好用

https://npm.taobao.org/package/ws

我做的websocket client就是将WebSocket-Node应用实例加了个json数据加密处理而已。应用实例几乎就是个通用模板。

protocal.js

var tick = {
    "protocolHead": "abc", 
    "protocolType": 0001
}

var login = {
    "protocolHead": "abc", 
    "protocolType": 0002, 
    "userName": "user", 
    "passWord": "123", 
    "mDeviceNumber": "65535"
}

module.exports.login = login;
module.exports.tick = tick;

des3.js

var crypto = require('crypto');  

exports.des3Encrypt = function(param) {  
    var key = new Buffer(param.key);  
    var iv = new Buffer(param.iv ? param.iv : 0)  
    var plaintext = param.plaintext  
    var alg = param.alg  
    var autoPad = param.autoPad  
 
    var cipher = crypto.createCipheriv(alg, key, iv);  
    cipher.setAutoPadding(autoPad)
    var ciph = cipher.update(plaintext, 'utf8', 'base64');  
    ciph += cipher.final('base64');   
    return ciph;

};  

exports.des3Decrypt = function(param) {  
    var key = new Buffer(param.key);  
    var iv = new Buffer(param.iv ? param.iv : 0)  
    var plaintext = param.plaintext  
    var alg = param.alg  
    var autoPad = param.autoPad  
 
    var decipher = crypto.createDecipheriv(alg, key, iv);  
    decipher.setAutoPadding(autoPad)  
    var txt = decipher.update(plaintext, 'base64', 'utf8');  
    txt += decipher.final('utf8');      
    return txt;  
}; 

websocket_client.js

var des3 = require('./des3.js');
var proto = require('./protocal.js');

var W3CWebSocket = require('websocket').w3cwebsocket;

var key_value = '0123456789abcdefghijklmn';

var client = new W3CWebSocket('ws://server_ip:port/folder', '');

function des3_decode(data){
    var para = {
        alg:'des-ede3',
        autoPad:true,
        plaintext:data,
        iv:null,
        key:key_value
    };
    var decode_str = des3.des3Decrypt(para);
    return decode_str;
}

function des3_encode(data){
    var para = {
        alg:'des-ede3',
        autoPad:true,
        plaintext:data,
        iv:null,
        key:key_qbox10
    };
    var encode_str = des3.des3Encrypt(para);
    return encode_str;
}

function recv_routine(data){
    var obj = JSON.parse(des3_decode(data));
    console.log("<<<<<<<<<<<<<<<<<<<<"+JSON.stringify(obj));
}

function tick_routine(){
    client.send(des3_encode(JSON.stringify(proto.tick)));
    console.log(">>>>>>>>>>>>>>>>>>>>"+JSON.stringify(proto.tick));
}

client.onerror = function() {
    console.log('Connection Error');
};

client.onopen = function() {
    console.log('WebSocket Client Connected');

    function send() {
        if (client.readyState === client.OPEN) {
            client.send(des3_encode(JSON.stringify(proto.login)));
            setInterval(tick_routine, 10000);
        }
    }
    send();
};

client.onclose = function() {
    console.log('Client Closed');
};

client.onmessage = function(e) {
    if (typeof e.data === 'string') {
        recv_routine(e.data);    
    }
};

 

 2)也有c语言实现websocket,非常繁琐,像下面这样,不推荐使用。

Linux下c语言实验Websocket通讯 含客户端和服务器测试代码
http://blog.csdn.net/SGuniver_22/article/details/74273839
Linux下用C编写WebSocet服务以响应HTML5的WebSocket请求
http://blog.csdn.net/xxdddail/article/details/19070149

 

3) addon c++编译

nodejs的C/C++拓展,将c/c++源码编译成js模板库
node-gyp configure
node-gyp build

交叉编译

export CC=arm-linux-gnueabihf-gcc
export CXX=arm-linux-gnueabihf-g++
export LD=arm-linux-gnueabihf-ld
export RAINLIB=arm-linux-gnueabihf-rainlib
export AR=arm-linux-gnueabihf-ar
export LINK=arm-linux-gnueabihf-g++
node-gyp configure --arch=arm
node-gyp build --arch=arm

 

4) nodejs库安装,编译

npm rebuild

npm init
npm install -save websocket
npm install ref-array
npm install -save ref-array
npm install -save ref-struct

交叉编译

npm init
npm install -save websocket --arch=arm
npm install ref-array --arch=arm

npm rebuild

5)nodejs源码交叉编译

node-ffi交叉编译

cd node-ffi
node-gyp --arch arm configure build

6)整理的交叉编译环境变量设置脚本

#!/bin/bash
export HOST=arm-linux-gnueabihf
export CPP="${HOST}-gcc -E"
export STRIP="${HOST}-strip"
export OBJCOPY="${HOST}-objcopy"
export AR="${HOST}-ar"
export RANLIB="${HOST}-ranlib"
export LD="${HOST}-ld"
export OBJDUMP="${HOST}-objdump"
export CC="${HOST}-gcc"
export CXX="${HOST}-g++"
export NM="${HOST}-nm"
export AS="${HOST}-as"

 

2、如果设计的是websocket服务器,websocket-bench用来做websocket的压力测试非常方便。

 

参考文献

1)WebSocket学习笔记——无痛入门

https://blog.csdn.net/xukai871105/article/details/23301213

2) Nodejs实现websocket的4种方式

https://blog.csdn.net/zhangyuan19880606/article/details/51517944

posted @ 2018-04-15 14:11  dong1  阅读(273)  评论(0编辑  收藏  举报