socket.io:如何放弃url:port方案?

时间:2013-05-01 01:21:57

标签: javascript html5 node.js socket.io

我开始玩node.js和socket.io并且无法弄清楚如何制作它所以你不必在浏览器中键入“url:port”而只是输入url。相反,我想只输入网址,然后一切都应该出现,就像在我未完成的单人游戏中一样:http://space.bonsaiheld.org/(你猜对了:我想让它成为多人游戏)。游戏不能在端口80/443上运行,因为这些端口专用于网络服务器。

它应该是这样的:http://ondras.zarovi.cz/games/just-spaceships/而不是“ip / url:port”。怎么做?

app.js

// Socket.IO
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs');

// Start the server on port 9000
app.listen(9000);

// Send index.html to the player
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);
  });
}

// Connection listener
io.sockets.on('connection', function (client)
{
    console.log('New connection established.');
}); // Connection listener

的index.html

   <html>
    <head>
    <meta charset="utf-8">
    <title>Mehrspielerklötzchen</title>
    <script src="/socket.io/socket.io.js"></script>
    </head>
    <body>
    <canvas id="canvas" style="background: #000000;">
    <script>

    // Socket.IO
    var socket = io.connect('http://localhost:9000');

    </script>
    </body>
    </html>
编辑:我基本上希望游戏在端口9000上运行,但是index.html可以通过普通/无端URL访问,例如sub.domain.com/game/而不是URL:端口。

编辑2:将问题简化为只有一个,因为我的两个问题恰好是单独的问题。

编辑3:解决了!我自己想出来了,这很简单:

新的极简化服务器代码:

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

// Connection listener
io.sockets.on('connection', function (client)
{
    console.log('Connection established.');
}); // Connection listener

新的index.html(可通过文件访问://folder/index.html)

<html>
<head>
<meta charset="utf-8">
<title>Mehrspielerklötzchen</title>
<script src="http://localhost:9000/socket.io/socket.io.js"></script>
</head>
<body>
<canvas id="canvas" style="background: #000000;">
<script>

// Socket.IO
var socket = io.connect('http://localhost:9000');

</script>
</body>
</html>

感谢所有帮助过的人。我想它也适用于端口重定向。但似乎我甚至不需要它。现在Apache一如既往地提供文件,但socket.io监听端口9000,index.html(或我想要的任何文件)连接到服务器!这也意味着此文件现在可以无处不在,即使在另一台服务器或本地也是如此。完善。 :))

1 个答案:

答案 0 :(得分:1)

使用默认的HTTP / HTTPS端口80/443(也是WS / WSS的默认端口)。

当然,你可以redirect将它们转移到其他“内部”端口。

相关问题