与'ws:// localhost:3000 /'的WebSocket连接失败:在收到握手响应之前连接已关闭 [英] WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

查看:2743
本文介绍了与'ws:// localhost:3000 /'的WebSocket连接失败:在收到握手响应之前连接已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拍了一个我朋友制作的游戏,希望通过WebRTC和websockets在对等体之间发送按键数据,让它可以跨浏览器播放。但是,我在控制台中收到此错误:

I took a game that my friend made and wanted to make it playable across browsers by sending keypress data between peers with WebRTC and websockets. However, I get this error in the console:


与'ws:// localhost:3000 /'的WebSocket连接失败:连接关闭之前收到握手响应

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

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

My server file has the following few lines:

'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;
      }
   });

连接的客户端看起来如下:

And the client side of the connection looks as follows:

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);

.....

这是错误发生的点,这是我得到的捕获错误:

This is the point that the error occurs and this is the caught error that I get:

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

I am not too familiar with server side programming and was trying to understand. I tried looking up this issue, but it seems like a variety of different things can cause this. If you want to see the repository you can see and try it yourself (uses webpack): SlidingWarfare Repo

推荐答案

混乱从这里开始:

const server = express();

express 函数并没有真正返回一台服务器,它返回一个应用程序。通常,用于此的变量是 app ,但这当然不过是约定(即不是要求)。

The express function doesn't really return a server, it returns an application. Commonly, the variable used for this is app, but that's of course nothing more than convention (i.e. not a requirement).

但是,将应用程序传递给WS服务器时会出现问题:

However, it becomes an issue when you pass the app to the WS server:

const wss = new SocketServer({ server });

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

That's because SocketServer requires an HTTP server instance, which server is not.

这是一个修复,没有重命名变量:

Here's a fix, without renaming your variables:

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

(因为当你打电话给 .listen()在Express实例上,它将返回一个HTTP服务器实例)

(because when you call .listen() on the Express instance, it will return an HTTP server instance)

使用变量命名约定,它将是:

Using the variable naming convention it would be this:

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 });

这篇关于与'ws:// localhost:3000 /'的WebSocket连接失败:在收到握手响应之前连接已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆