【发布时间】:2019-11-24 06:19:45
【问题描述】:
我在 DigitalOcean 上使用 Ubuntu 服务器来托管 Nginx Web 服务器和运行 WebSocket 服务器的 Node 应用程序。尝试连接到服务器的 IP 时,我在控制台中收到以下消息:
WebSocket connection to 'ws://<server's public IP>' failed: Error during WebSocket handshake: Unexpected response code: 200
我设置 Nginx 所做的只是关注this guide,它只是告诉你安装 Nginx 并调整 UFW 防火墙。我在第 4 步中没有设置服务器块,也没有触及任何其他配置文件。
之后,我将我的index.html 和client.js 文件放在/var/www/html 目录中,由Nginx 提供服务。
index.html 是一个运行client.js 的非常简单的HTML 页面。该 JS 文件如下所示:
const ws = new WebSocket('ws://<public IP, same as above>:80');
ws.addEventListener('open', () => {
const json = { message: 'hello from client!' };
const jsonString = JSON.stringify(json);
ws.send(jsonString);
});
ws.addEventListener('message', event => {
const data = JSON.parse(event.data);
console.log(data);
});
服务端 Node 应用是websocket.js,它看起来像这样:
const buffer = require('buffer');
const http = require('http').createServer();
const ws = require('ws');
const wsServer = new ws.Server({ server: http });
wsServer.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('received: ' + msg);
socket.send(Buffer.from('hello from the server!'));
});
const json = { message: 'hello from server!' };
const jsonString = JSON.stringify(json);
socket.send(Buffer.from(jsonString));
});
http.listen(8080, () => console.log('listening on 8080'));
此文件与node_modules、package.json 和package-lock.json 一起放置在/root。将它与/var/www/html 的客户端代码一起提供并没有帮助。当然,它也是通过 PM2 运行的,我也尝试在没有 PM2 的情况下运行。
感谢您的帮助,如果有任何我可能遗漏的信息,请告诉我。
【问题讨论】: