与一的NodeJS服务器上使用Apache使用socket.io作为反向代理(Using socke

2019-06-24 04:24发布

我试图使用Node.js的使用Socket.IO旨在便利浏览器和客户端之间的通讯,下面的指南 。

但是,我不得不设置节点反向代理后面的Apache。 所以,与其example.com:8080节点,我使用example.com/nodejs/。

这似乎导致Socket.IO失去本身的意义。 这里是我的节点应用程序

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

// this has to be here, otherwise the client tries to 
// send events to example.com/socket.io instead of example.com/nodejs/socket.io
io.set( 'resource', '/nodejs/socket.io' );

io.sockets.on('connection', function (socket) {

  socket.emit('bar', { one: '1'});

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

});

这里就是我的客户端文件的样子

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Socket.IO test</title>

  <script src="http://example.com/nodejs/socket.io/socket.io.js"></script>

  <script>

  var socket = io.connect('http://example.com/nodejs/');

  console.log( socket );

  socket.on( 'bar', function (data)
  {
    console.log(data);
    socket.emit( 'foo', {bar:'baz'} );
  });

  socket.emit('foo',{bar:'baz'});

  </script>
</head>
<body>
  <p id="hello">Hello World</p>
</body>
</html>

这里的问题是脚本参考http://example.com/nodejs/socket.io/socket.io.js 。 它不会返回预期的使用JavasScript内容-而是返回“欢迎来到socket.io”好像我打http://example.com/nodejs/ 。

任何想法,我怎样才能使这项工作?

Answer 1:

这结束了多管齐下的解决方案。

首先,对事物的服务器端,我不得不建立这样的端点

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

var rootSockets = io.of('/nodejs').on('connection', function(socket)
{
  // stuff
});

var otherSockets = io.of('nodejs/other').on('connection', function(socket)
{
  // stuff
});

然后,在客户端,以便正确地连接看起来像这样

var socket = io.connect(
    'http://example.com/nodejs/'
  , {resource: 'nodejs/socket.io'}
);

// The usage of .of() is important
socket.of('/nodejs').on( 'event', function(){} );
socket.of('/nodejs/other').on( 'event', function(){} );

在此之后,它的所有工作。 请记住,在此服务器上Apache是​​进行代理example.com/nodejs 8080端口内部。



Answer 2:

我不认为这有什么与你的Apache代理,但一些“怪癖”与如何处理socket.io一个子目录请求。 在这里见我的答案。 NGINX配置与Socket.IO工作

基本上,你需要使用这个连接语句来代替:

var socket = io.connect('http://example.com', {resource:'nodejs/socket.io'});



Answer 3:

如果有人有兴趣,只有这个工作对我来说。 与港口的NodeJS替换端口3000

阿帕奇2.2.14您的虚拟主机内

    <IfModule mod_proxy.c>
      <Proxy *>
        Order allow,deny
        allow from all
      </Proxy>
    </IfModule>

    RewriteEngine on

    RewriteCond %{QUERY_STRING} transport=polling
    RewriteRule /(.*)$ http://localhost:3001/$1 [P]

    ProxyRequests off
    ProxyPass /socket.io/ ws://localhost:3001/socket.io/
    ProxyPassReverse /socket.io/ ws://localhost:3001/socket.io/

客户端连接:

  var myIoSocket = io.connect($location.protocol() + '://' + $location.host(), {path: '/socket.io'});

没有必要改变对Node.js的侧东西。



文章来源: Using socket.io with nodejs on a server with apache as a reverse proxy