在 Node.js 中使用哪个 websocket 库? [打烊]

Currently there is a plethora of websocket libraries for node.js, the most popular seem to be:

However I can't find any solid concrete comparisons between any of them... Apparently Socket.io was awesome, but has become quite dated and has failing builds. Both ws and websocket-node claim they are the fastest. And engine.io seems new, but a lot heavier than the lighter aletarntives.

It would be amazing if we or someone could put together an answer that serves as a guide on which socket library to use and when, as well as a comparison between them.

转载于:https://stackoverflow.com/questions/16392260/which-websocket-library-to-use-with-node-js

csdnceshi72
谁还没个明天 if interested, heres why this got closed: meta.stackoverflow.com/questions/291052/… ( i think)
3 年多之前 回复
csdnceshi79
python小菜 For what it's worth, Socket.IO is solid. If you need browser compatibility, I recommend it. If you're looking for something pure websocket, use something else.
大约 7 年之前 回复
csdnceshi50
三生石@ I use Primus with ws these days, as ws is all I needed, if I need something more extreme, I just swap out the undering library and keep the same api thanks to Primus. Works wonders.
大约 7 年之前 回复
csdnceshi64
游.程 can you update the community with your choice and if you are happy with it? is it socket.io?
大约 7 年之前 回复
csdnceshi80
胖鸭 I agree, I would like to see this kind of question not just allowed, but encouraged. OK, they may not be relevant in a years time, but till then they will save the world.
7 年多之前 回复
csdnceshi50
三生石@ Woot woot for community wikis, meaning that despite the question being closed from new answers, we can still improve the community wiki answer below :)
7 年多之前 回复
csdnceshi50
三生石@ If this gets closed, where should a question like this go? As the answer will be incredibly useful... Seems unfortunate that such a prominent question shouldn't reside here.
7 年多之前 回复

3个回答

Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.

  • ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.

  • websocket-node WebSocket server and client for node.js

  • websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node

  • faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs

  • socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.

  • sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks

  • faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages

  • deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response

  • socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.

  • primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.

When to use:

  • use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities

  • use the fallback libraries when you care about browser fallbacks

  • use the full featured libraries when you care about channels

  • use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.

weixin_41568174
from.. I've tried ws, and it doesn't seem to work very well for streaming. If it falls behind on messages, it groups them into one and then acts as if it was posted multiple times. You can write code to figure out when it's doing that and ignore messages, or use something else.
大约 3 年之前 回复
weixin_41568196
撒拉嘿哟木头 Deepstream.io server no longer works on Node.js, you now have to run it as a separate service and then add a Deepstream.io client onto Node.js to communicate with the server.
3 年多之前 回复
csdnceshi64
游.程 -- me too: "what do you mean by 'channels'"? Maybe it's the concept of a channel in the context of a messaging system, as seen on this JBoss site "different message channels provides an elementary way of sorting messages into different message types." I still dunno what it means in context of WebSockets, except for this websocket-rails doc
3 年多之前 回复
csdnceshi61
derek5. WAMP is a subprotocol of WebSocket, not a WS library. op asked specifically about the latter.
4 年多之前 回复
csdnceshi67
bug^君 A small detail for ws is that it needs python. So if you deploy on docker containers or something, you'll need to have python available to use ws.
5 年多之前 回复
csdnceshi51
旧行李 Channels is the so called 'rooms' each player in a room can exchange messages..
大约 6 年之前 回复
csdnceshi71
Memor.の Nice list of all available option after death of now.js
6 年多之前 回复
csdnceshi56
lrony* What about Autobahn/WAMP?
6 年多之前 回复
csdnceshi68
local-host Thanks for the detailed answer. Can you explain point 3 in when to use. What are the channels that the point is referring to? I am new to websockets and am trying to understand which one to use in my case.
大约 7 年之前 回复

Update: This answer is outdated as newer versions of libraries mentioned are released since then.

Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.

"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.

See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539

csdnceshi56
lrony* Socket.IO released its v1. Engine.io is not a replacement for it, but used internally by Socket.IO as the transport protocol - it abstracts the actual communication between endpoints (xhr,ws) and has a simple format for packets. Socket.io provides a richer api that 'feels' like an event emitter over the wire.
6 年多之前 回复
csdnceshi51
旧行李 Do you have any insights/experience with Autobahn/WAMP (wamp.ws)?
6 年多之前 回复
weixin_41568208
北城已荒凉 This reminds me of the usual Node.js 0.12 is immediate … they also claim that for months now. So, probably, we'll have to wait and see…
6 年多之前 回复

npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.

var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;

var app = express();
    app.use(express.static(__dirname+ "/../"));
    app.get('/someGetRequest', function(req, res, next) {
       console.log('receiving get request');
    });
    app.post('/somePostRequest', function(req, res, next) {
       console.log('receiving post request');
    });
    app.listen(80); //port 80 need to run as root

    console.log("app listening on %d ", 80);

var server = http.createServer(app);
    server.listen(port);

console.log("http server listening on %d", port);

var userId;
var wss = new WebSocketServer({server: server});
    wss.on("connection", function (ws) {

    console.info("websocket connection open");

    var timestamp = new Date().getTime();
    userId = timestamp;

    ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));


    ws.on("message", function (data, flags) {
        console.log("websocket received a message");
        var clientMsg = data;

        ws.send(JSON.stringify({msg:{connectionId:userId}}));


    });

    ws.on("close", function () {
        console.log("websocket connection close");
    });
});
console.log("websocket server created");
csdnceshi69
YaoRaoLov using express-ws allows to add ws routes in express app.
接近 4 年之前 回复
weixin_41568110
七度&光 you can simulate routes if you want it.
接近 4 年之前 回复
csdnceshi52
妄徒之命 Actually WebSocket endpoints have url too, they start with ws, such as ws://myserver.com. And yes, they can be configured to be served using 80 and 443 ports too. Using a reverse proxy like nginx, you can route the WebSocket protocol urls to another port from the normal HTTP protocols.
接近 5 年之前 回复
csdnceshi77
狐狸.fox there is no request url as in ajax requests. The javascript library open a connection to your web-socket server using the an address such 127.0.0.1:8080 or anything.com:7777 , etc... . It is sounds confusing, try to go through some simple tutorial on web-sockets.
5 年多之前 回复
csdnceshi60
℡Wang Yan How to get request url in connection metod? wss.on("connection", function (ws) { // some code console.log(ws.???) get url... }
5 年多之前 回复
立即提问
相关内容推荐