在服务器上使用带有nodejs的socket.io,并使用apache作为反向代理

Pet*_*ley 10 reverse-proxy node.js socket.io

我正在尝试使用Node.js和Socket.IO来按照指南在浏览器和客户端之间进行消息传递.

但是,我必须在Apache后面设置Node反向代理.因此,对于节点而不是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 );
  });

});
Run Code Online (Sandbox Code Playgroud)

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

<!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>
Run Code Online (Sandbox Code Playgroud)

这里的问题是http://example.com/nodejs/socket.io/socket.io.js的脚本引用.它不会返回预期的javasscript内容 - 而是返回"Welcome to socket.io",就好像我点击http://example.com/nodejs/一样.

知道如何让这个工作吗?

Pet*_*ley 9

这最终成为一个多管齐下的解决方案.

首先,在服务器端,我必须像这样设置端点

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
});
Run Code Online (Sandbox Code Playgroud)

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

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(){} );
Run Code Online (Sandbox Code Playgroud)

在此之后,一切都奏效了.请记住,在此服务器上,Apache在内部将example.com/nodejs代理到端口8080.

  • 你用过哪个版本的socket.io?我试过提到的解决方案.但是,如果通过apache mod_proxy路由Web套接字请求,则会删除所有http标头.因此,socket.io将连接关闭为"websocket连接无效". (2认同)