【问题标题】:when trying connecting to server.. failed: Error during WebSocket handshake: Unexpected response code: 404尝试连接到服务器时..失败:WebSocket 握手期间出错:意外的响应代码:404
【发布时间】:2020-03-08 22:55:03
【问题描述】:

与“ws://localhost:8080/Index.html/ETOM/chat/sara”的 WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:404

ws = new WebSocket("ws://" + document.location.host + "/Index.html/ETOM2.0/chat/" + username);

【问题讨论】:

  • 你确定你有一个 websocket 服务器在 localhost:8080 监听吗?
  • document.location.host = localhost:8080
  • 你的错误说:ws://localhost:8080/Index.html/ETOM ...你的配置说“ws://”+document.location.host+“/Index.html/ ETOM2.0 ...
  • 您的错误信息中的 2.0 在哪里?
  • 但是您的错误信息显示它正在尝试连接到 ETOM 而不是 ETOM2.0,您确定 URL 正确吗?

标签: javascript websocket


【解决方案1】:

2020 年 9 月更新(Express + socket 相同端口)

对于所有新来者来说,试试这个:

//Back-End Node.js
const app = require("express")(); /*Running it right away*/
const server = require("http").Server(app);/*Use server Function and pass The app To It*/
var io = require("socket.io")(server);
const port = 3000;

app.get("/", (req, res) => {
});


server.listen(port, () => {
 console.log("app listening on port 3000 in");
});


io.on("connection", (socket) => {
  console.log("user connected");
  socket.emit("message", { backend: "hey how are you?" });
  socket.on("another event", (data) => {
   console.log(data);
  });
});

//Front-End ES6
import io from "socket.io-client";
var socket = io("ws://localhost:3000", { transports: ["websocket"] });
socket.on("message", (data) => {
 console.log(data);
 socket.emit("another event", { frontend: "I am great thank you" });
});

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 1970-01-01
    • 2020-04-14
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    相关资源
    最近更新 更多