套接字.io:如何放弃url:port模式

socket.io: How to abandon the url:port scheme?

本文关键字:url port 放弃 模式 io 何放弃 套接字      更新时间:2023-09-26

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

应该是这样的: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(可通过file://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像往常一样提供文件,除了套接字。IO监听端口9000,index.html(或我想要的任何文件)连接到服务器!这也意味着这个文件现在可以在任何地方,甚至在另一个服务器或本地。完美的。:))

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

当然你也可以将它们重定向到其他"内部"端口