javascript – Node.js Socket.io Apache

前端之家收集整理的这篇文章主要介绍了javascript – Node.js Socket.io Apache前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种方法来以下列方式集成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.

有什么建议?韩国社交协会.

解决方法

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

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');
  });
});

猜你在找的JavaScript相关文章