简体   繁体   English

如何获取 socket.io 客户端

[英]how to get socket.io client

i wanted to build socket.io server and when setting up the client i have an error (on the client side) Failed to load resource:http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OK-egu3 the server responded with a status of 404 (Not Found)我想构建 socket.io 服务器,在设置客户端时出现错误(在客户端) Failed to load resource:http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OK-egu3 the server responded with a status of 404 (Not Found)

code: server.js:代码:server.js:

const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {cors: {origin: "*"}});
const path = require('path');

app.set('view engine', 'ejs');

app.use(express.json({extended: true, limit: '1mb'}));

io.on('connection', (socket) => {
 console.log("new connection " + socket);
});

app.get("/", (req, res, next) => {
 res.render('index'/*, { ioS : io }*/);
});

console.log("Ready");

app.listen(3000);

index.ejs:索引.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>socket Respons</h1>
</body>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
<script>
    //const io = ;
    const socket = io();
    console.log(socket);
</script>
</html>

i have installed the following liblaries:我已经安装了以下库:

socket.io socket.io-client express ejs socket.io socket.io-客户端 express ejs

You're not initializing the client correctly.您没有正确初始化客户端。 Your server is at localhost:3000, but the client doesn't know that, because you haven't told it where to look.您的服务器位于 localhost:3000,但客户端不知道,因为您没有告诉它去哪里查找。

Looking at the socketio documentation , you need to pass the URL of the server's socket endpoint:查看socketio 文档,您需要传递服务器套接字端点的 URL:

const URL = "http://localhost:3000";
const socket = io(URL, { autoConnect: false });

It's worth mentioning that the error message indicates this: "not found."值得一提的是,错误消息表明:“未找到”。 It's not a verbose error message, but it's a valuable debugging signal.这不是一条冗长的错误消息,而是一个有价值的调试信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM