目前有一个过多的websocket库 for node.js,最流行的似乎是:
不过,我找不到他们之间任何一个具体的比较.显然,Socket.io很棒,但是它已经过时了,并且有失败的构建。ws和websocket节点都声称它们是最快的。engine.io似乎是新的,但比较轻的产品要重得多。
如果我们或某个人能把一个答案放在一起,作为使用哪一个套接字库和何时使用的指南,以及它们之间的比较,那就太棒了。
发布于 2014-10-01 08:10:11
npm是我的答案。我发现它不那么有侵扰性,更直截了当。同时,将websockets与rest服务混为一谈也很简单。在这个帖子上共享简单代码。
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");https://stackoverflow.com/questions/16392260
复制相似问题