0

我正在开发一个多人 HTML5 游戏,使用 Node.js 作为 Express 服务器,使用 Socket.io 作为 websockets。当我尝试在浏览器中访问应用程序正在侦听的端口中的游戏时,我得到一个空白页面。但是,当我直接访问 index.html 文件时(在服务器运行时),它可以完美运行。

请注意,当我说“直接访问文件”时,我的意思是:file:///C:/Program%20Files/nodejs/SupermarketChallenge/public/index.html

这很好,直到我想和我的室友一起测试游戏,他需要通过 localhost 访问它才能玩!

这是相关的服务器代码:

var express = require('express'),
    //Create an express server
    app = express.createServer(),
    //attach socket.io to the server
    supermarket = require('socket.io').listen(app);

//Configure a static directory for public files
app.configure(function() {
    app.use(express.static(__dirname + '/public'));
});

//set the port to listen to
app.listen(3000);

和客户:

var socket = io.connect('http://localhost:3000'); 
4

2 回答 2

0

这是因为 go tohttp://localhost:3000/与您的公用文件夹中的任何有效文件都不匹配。你需要一条路线来匹配这个。根据以下内容更新您的代码:

var express = require('express'),
    //Create an express server
    app = express.createServer(),
    //attach socket.io to the server
    supermarket = require('socket.io').listen(app);

//Routes
app.get('/', function(req, res) {
    res.redirect('/index.html');
});

//Configure a static directory for public files
app.configure(function() {
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

//set the port to listen to
app.listen(3000);

现在可以更改您的路线以实际提供 的内容index.html,在这种情况下,您可以将/路线替换为以下内容:

//Routes
app.get('/', function(req, res) {
    res.sendfile(__dirname + '/public/index.html');
});
于 2012-11-16T16:04:36.830 回答
0
const app = require("express")();
const httpServer = require("http").createServer(app);
const options = { /* ... */ };
const io = require("socket.io")(httpServer, options);

io.on("connection", socket => { /* ... */ });

httpServer.listen(3000);
// WARNING !!! app.listen(3000); will not work here, as it creates a new HTTP server
于 2021-06-19T13:43:10.447 回答