作为反向代理的服务器上使用带有

作为反向代理的服务器上使用带有

本文介绍了在以 apache 作为反向代理的服务器上使用带有 nodejs 的 socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Node.js 和 Socket.IO 来促进浏览器和客户端之间的消息传递,遵循 指南.

I'm attempting to use Node.js with Socket.IO to faciliate messaging between the browser and client, following the guide.

但是,我必须在 Apache 后面设置 Node 反向代理.因此,我使用的是 example.com/nodejs/,而不是 node 的 example.com:8080.

However, I had to setup Node reverse-proxied behind Apache. So, instead of example.com:8080 for node, I'm using example.com/nodejs/.

这似乎导致 Socket.IO 失去了自我意识.这是我的节点应用

This seems to cause Socket.IO to lose sense of itself. Here's my node app

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

});

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

And here's what my client file looks like

<!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.它不会返回预期的 javascript 内容——而是返回欢迎使用 socket.io",就像我点击了 http://example.com/nodejs/.

The problem here is the script reference to http://example.com/nodejs/socket.io/socket.io.js. It doesn't return the expected javasscript content - instead it returns "Welcome to socket.io" as if I hit http://example.com/nodejs/.

知道如何使这项工作成功吗?

Any idea how I can make this work?

推荐答案

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

This ended up being a multi-pronged solutions.

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

First, on the server end of things, I had to set up the endpoints like this

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

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

Then, on the client-side, to properly connect looks like this

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.

After this, it all worked. Remember, on this server Apache is proxying example.com/nodejs to port 8080 internally.

这篇关于在以 apache 作为反向代理的服务器上使用带有 nodejs 的 socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 00:05