小编典典

Node.js + Socket.io + Apache

node.js

我正在寻找一种通过以下方式集成Node.js + Socket.io + Apache的方法:我希望apache继续提供HTML /
JS文件。我希望node.js侦听端口8080上的连接。如下所示:

var util = require("util"),
    app = require('http').createServer(handler),
    io = require('/socket.io').listen(app),
    fs = require('fs'),
    os = require('os'),
    url = require('url');

app.listen(8080);

function handler (req, res) {

    fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });

  socket.on('my other event', function (data) {
    socket.emit('ok 1', { hello: 'world' });
  });

  socket.on('clientMSG', function (data) {
    socket.emit('ok 2', { hello: 'world' });
  });

});

如果我访问连接到该服务器的HTML,它可以工作,但是我需要转到mydomian.com:8080/index.html。我想要的是能够去mydomian.com/index.html。并能够打开套接字连接:

<script>
        var socket = io.connect('http://mydomain.com', {port: 8080});
        socket.on('news', function (data) {
            console.log(data);
            socket.emit('my other event', { my: 'data from the client' });
        });

        socket.on('connect', function (data) {
            console.log("connect");
        });

        socket.on('disconnect', function (data) {
            console.log("disconnect");
        });


            //call this function when a button is clicked
        function sendMSG()
        {
            console.log("sendMSG"); 
            socket.emit('clientMSG', { msg: 'non-scheduled message from client' });
        }

    </script>

在此示例中,当我转到URL的端口8080时,我必须使用不会工作的fs.readFile。

有什么建议?Tks。


阅读 265

收藏
2020-07-07

共1个答案

小编典典

从Apache端口80提供静态内容,并在端口8080上的Socket.IO服务器上提供动态/数据内容app = require('http').createServer(handler)。Socket.IO应用程序中不需要

Apache端口80 | ------------- | 客户| ------------ | Socket.IO端口8080

var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
  io.sockets.emit('this', { will: 'be received by everyone'});

  socket.on('clientMSG', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
  });

  socket.on('disconnect', function () {
    sockets.emit('user disconnected');
  });
});
2020-07-07