gpt4 book ai didi

javascript - WebSocket 连接到 'ws://localhost:3000/' 失败 : Connection closed before receiving a handshake response

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:59 24 4
gpt4 key购买 nike

我玩了一个 friend 制作的游戏,并希望通过使用 WebRTC 和 websockets 在对等点之间发送按键数据来使其可以跨浏览器玩。但是,我在控制台中收到此错误:

WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

我的服务器文件有以下几行:

'use strict';

const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');

const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');

const server = express();

server.use(express.static(path.join(__dirname, 'lib')));
server.use('/assets', express.static(path.join(__dirname, 'assets')));
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const wss = new SocketServer({ server });
var users = {};
let usernames = [];


wss.on('connection', function(connection) {

connection.on('message', function(message) {

var data;
try {
data = JSON.parse(message);
} catch (e) {
console.log("Invalid JSON");
data = {};
}

switch (data.type) {
case "login":
console.log("User logged", data.name);
if(users[data.name]) {
sendTo(connection, {
type: "login",
success: false
});
} else {
users[data.name] = connection;
connection.name = data.name;
usernames.push(data.name);

sendTo(connection, {
type: "login",
success: true,
users: usernames
});
}

break;

case "offer":
console.log("Sending offer to: ", data.name);
var conn = users[data.name];

if(conn != null) {
connection.otherName = data.name;

sendTo(conn, {
type: "offer",
offer: data.offer,
name: connection.name
});
}

break;

case "answer":
console.log("Sending answer to: ", data.name);
var conn = users[data.name];

if(conn != null) {
connection.otherName = data.name;
sendTo(conn, {
type: "answer",
answer: data.answer
});
}

break;

case "candidate":
console.log("Sending candidate to:",data.name);
var conn = users[data.name];

if(conn != null) {
sendTo(conn, {
type: "candidate",
candidate: data.candidate
});
}

break;

case "leave":
console.log("Disconnecting from", data.name);
var conn = users[data.name];
conn.otherName = null;

if(conn != null) {
sendTo(conn, {
type: "leave"
});
}

break;

default:
sendTo(connection, {
type: "error",
message: "Command not found: " + data.type
});

break;
}
});

连接的客户端如下所示:

const Game = require("./game");
const GameView = require("./game_view");
var HOST = location.origin.replace(/^http/, 'ws');
console.log('host: ', HOST);
console.log(process.env.PORT);

document.addEventListener("DOMContentLoaded", function() {
const connection = new WebSocket(HOST);

.....

这是错误发生的地方,这是我捕获到的错误:

bubbles
:
false
cancelBubble
:
false
cancelable
:
false
composed
:
false
currentTarget
:
WebSocket
defaultPrevented
:
false
eventPhase
:
0
isTrusted
:
true
path
:
Array(0)
returnValue
:
true
srcElement
:
WebSocket
target
:
WebSocket
timeStamp
:
213.01500000000001
type
:
"error"
__proto__
:
Event

我不太熟悉服务器端编程,正在尝试理解。我尝试查找此问题,但似乎有多种不同的原因会导致此问题。如果您想查看存储库,您可以自己查看并尝试(使用 webpack):SlidingWarfare Repo

最佳答案

困惑从这里开始:

const server = express();

express 函数实际上并没有返回一个服务器,它返回一个应用程序。通常,用于此的变量是 app,但这当然只是约定俗成的(即不是必需的)。

但是,当您将应用程序传递到 WS 服务器时,它会成为一个问题:

const wss = new SocketServer({ server });

那是因为 SocketServer 需要一个 HTTP 服务器实例,而 server 不需要。

这是一个修复方法,无需重命名您的变量:

let httpServer = server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
...
const wss = new SocketServer({ server : httpServer });

(因为当您在 Express 实例上调用 .listen() 时,它将返回一个 HTTP 服务器实例)

使用变量命名约定应该是这样的:

const app = express();

app.use(express.static(path.join(__dirname, 'lib')));
app.use('/assets', express.static(path.join(__dirname, 'assets')));

let server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const wss = new SocketServer({ server });

关于javascript - WebSocket 连接到 'ws://localhost:3000/' 失败 : Connection closed before receiving a handshake response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44977916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com