【问题标题】:Socket.io can't find localhostSocket.io 找不到本地主机
【发布时间】:2021-08-20 05:52:12
【问题描述】:

我正在关注this basic tutorial,当我很快发现 socket.io 似乎没有检测到我的 index.html 并且 localhost 给出错误消息 404。所以也许我输入了错误的东西,因此我复制了 the files 来自教程,但同样的问题仍然存在。我错过了什么?

【问题讨论】:

  • 仅供参考,该教程没有提供实际加载 index.html 的方法,因为该示例中的简单服务器只是一个 socket.io 服务器,并且没有可以服务 index.html 的常规 http 服务器。那么,你是如何加载 index.html 的呢?
  • 我认为 socket.io 会像 express 一样加载它。
  • 没有。 socket.io 只响应 socket.io 请求,而不是常规的网页请求。访问 socket.io 网站,了解如何使用 socket.io WITH Express 的示例,例如 here
  • 我明白了,谢谢。奇怪的是教程怎么缺少...

标签: node.js socket.io localhost http-status-code-404


【解决方案1】:

Socket.io 本身只响应 socket.io 请求,而不是常规的网页请求。因此,如果您希望您的服务器既可以与 socket.io 一起使用,又可以作为常规 Web 服务器来提供网页服务,那么您需要将常规 Web 服务器与您的 socket.io 代码集成在一起。

socket.io 网站上有一个如何使用 socket.io WITH Express 的示例,例如here。基本概念(来自 socket.io 文档)是这样的:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

【讨论】:

    猜你喜欢
    • 2012-07-26
    • 2019-11-09
    • 2014-02-10
    • 2019-06-29
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多