怎么让 nodejs-websocket 启动的ws服务与http启动的http服务共用一个端口呢?
发布于 3 个月前 作者 tomoya92 802 次浏览 来自 问答

nodejs-websocket 创建服务

var ws = require("nodejs-websocket")
 
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
    console.log("New connection")
    conn.on("text", function (str) {
        console.log("Received "+str)
        conn.sendText(str.toUpperCase()+"!!!")
    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(8001)

http 创建服务

const http = require("http");
const fs = require("fs");

http
  .createServer(function(req, res) {
    res.writeHead(200, { "Content-Type": "text/html" });
    var stream = fs.createReadStream("./index.html");
    stream.on("open", function(fd) {
      // console.log('开始读取文件');
    });
    stream.on("data", function(data) {
      // console.log('读取到数据:');
      // console.log(data.toString());
      res.write(data);
    });
    stream.on("end", function() {
      // console.log('文件已全部读取完毕');
      res.end();
    });
    stream.on("close", function() {
      // console.log('文件被关闭');
    });
    stream.on("error", function(err) {
      // console.log('读取文件失败');
      res.writeHead(500, { "Content-Type": "text/html" });
      res.write("500 error");
    });
  })
  .listen(3000);

有办法把这两个端口共用吗?

2 回复
/**
 * HTTP server
 */
var server = http.createServer(function(request, response) {
    // Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
    console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});

/**
 * WebSocket server
 */
var wsServer = new webSocketServer({
    // WebSocket server is tied to a HTTP server. WebSocket request is just
    // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
    httpServer: server
});

https://www.npmjs.com/package/websocket 用的是这个库

socket.io 可以,不过魔改了 websocket

回到顶部