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

£可爱£侵袭症+ 提交于 2019-11-30 21:24:49

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 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!