μWebSockets.js 介绍
发布于 2 年前 作者 yviscool 9772 次浏览 来自 分享

最近看到一份 web 框架性能对比, 结果如下 image.png

心想这个 nanoexpress 是个啥, 咋从来没听过. 看了看了他就是套了一层 μWebSockets.js. 那么 μWebSockets.js 又是什么鬼

μWebSockets.js 是一个 C++ 写的 node 扩展. 一个 Node 的 HTTP /WebSocket 服务器. 据他官网吹的说 http 方面是 Fastify 的 8.5 倍,WebSocket 至少是 Socket.IO 的 10 倍. 恐怖如斯.

简单的使用如下

/* Non-SSL is simply App() */
require('uWebSockets.js').SSLApp({

  /* There are more SSL options, cut for brevity */
  key_file_name: 'misc/key.pem',
  cert_file_name: 'misc/cert.pem',
  
}).ws('/*', {

  /* There are many common helper features */
  idleTimeout: 30,
  maxBackpressure: 1024,
  maxPayloadLength: 512,
  compression: DEDICATED_COMPRESSOR_3KB,

  /* For brevity we skip the other events (upgrade, open, ping, pong, close) */
  message: (ws, message, isBinary) => {
    /* You can do app.publish('sensors/home/temperature', '22C') kind of pub/sub as well */
    
    /* Here we echo the message back, using compression if available */
    let ok = ws.send(message, isBinary, true);
  }
  
}).get('/*', (res, req) => {

  /* It does Http as well */
  res.writeStatus('200 OK').writeHeader('IsExample', 'Yes').end('Hello there!');
  
}).listen(9001, (listenSocket) => {

  if (listenSocket) {
    console.log('Listening to port 9001');
  }
  
});

依赖大小如下. image.png

然后这个 nanoexpress 类似 express, 基于 μWebSockets.js 做的封装 类似的还有一个 hyper-express. 两个性能看起来并驾齐驱. image.png

nanoexpress 基本使用

import nanoexpress from 'nanoexpress';

const app = nanoexpress();

app.get('/', (req, res) => {
    return res.send({ status: 'ok' });
});

app.listen(3000);

hyper-express 基本使用

const HyperExpress = require('hyper-express');
const webserver = new HyperExpress.Server();

// Create GET route to serve 'Hello World'
webserver.get('/', (request, response) => {
    response.send('Hello World');
})

// Activate webserver by calling .listen(port, callback);
webserver.listen(80)
.then((socket) => console.log('Webserver started on port 80'))
.catch((error) => console.log('Failed to start webserver on port 80'));

不过这两个周边生态基本为零, 看起来只能写一些 crud . image.png

后面又搜了搜, 发现这个 uWebSockets 作者有点前科, 到处去 diss, 比如各个 websocket 框架, deno 下面 也不在 npm 发包, 只在 github 上.
所以这两个框架依赖都是 github url 的形式的.

nanoexpress 有好几个版本, 旗舰版, 企业版. 前两年还是闭源的状态, 要收费的, 定制一些中间件之类的. 看起来不像真的开源. hyper-express 倒是好一点, 没有一些乱七八糟的的.

有兴趣的伙伴可以看看

5 回复

老实说我其实特别反对应用走C++扩展,走wasm不香么,这样可以不需要再不同的环境编译,直接解决兼容问题不好么。为了这一点点性能造成维护成本陡增实属没有必要。当然和V8强绑定不得不走C++扩展则另说。

怎么说呢,我也实测和找过资料,NodeJS的封装确实是损失了好多性能,有兴趣的可以看看 https://github.com/just-js/just/issues/5 https://github.com/uNetworking/uWebSockets.js/discussions/341

本来我也反感这种到处去diss的行为的,但是直到我看到just-js的表现,也能够稍微理解这种行为了 为性能而生的v8给搞成这样了,有点遗憾

回到顶部