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

前端 未结 1 1408
时光取名叫无心
时光取名叫无心 2021-01-02 16:30

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

相关标签:
1条回答
  • 2021-01-02 16:48

    The confusion starts here:

    const server = express();
    

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

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

    const wss = new SocketServer({ server });
    

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

    (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 });
    
    0 讨论(0)
提交回复
热议问题