Websockets不能在nodejs应用和nextjs应用上工作



此代码位于我的nodejs后端(https://backend.example.com)server.js文件中:

const WebSocket = require('ws');
const server = new WebSocket.Server({
port: 7500
},
() => {
console.log('Server started on port 7500');
}
);

这个代码是在我的nextjs前端聊天(http://frontend.example.com/chat)页面文件:

React.useEffect(() => {
ws.current = new WebSocket("ws://localhost:7500");
ws.current.onopen = () => {
console.log("Connection opened");
setConnectionOpen(true);
};
ws.current.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((_messages) => [..._messages, data]);
};
return () => {
console.log("Cleaning up...");
ws.current.close();
};
}, []);

它在localhost中工作得很好,但在部署的实时服务器上,websocket不通信,我的代码有什么问题?

编辑:已将useEffect()更新为:

React.useEffect(() => {
ws.current = new WebSocket("wss://backend.example.com:7500");
ws.current.onopen = () => {
console.log("Connection opened");
setConnectionOpen(true);
};
ws.current.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((_messages) => [..._messages, data]);
};
return () => {
console.log("Cleaning up...");
ws.current.close();
};
}, []);

但仍然不起作用,如果我访问https://backend.example.com,我得到Upgrade Required

如果这是您在活动服务器上部署的代码,那么我认为必须解决以下几点:

在您指向localhost的客户机上,您应该有服务器名称,而不是。

更重要的是,在本地,你在http发布应用程序,而在实时服务器,它是在https?

在这种情况下,WebSocket url应该将协议从ws更改为wss

另一个注意点是你的服务器。

根据文档示例,我没有看到处理连接的代码。

import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
// This handle the co
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});

如果这不是你正在使用的库,请将你的问题更新为你正在使用的库的所有引用或你在编写代码时引用的文档。

关于端口,没有关于端口的具体信息,唯一的问题是您可以在客户端的防火墙或服务器的网络网关上阻止端口。

但这取决于您的环境,您应该检查端口是否可用。一个简单的测试是尝试在服务器的7500端口上发布一个html页面的小型服务器。如果您能看到该页面,则表示端口正常。

你更应该而不是使用服务器的相同端口,选择另一个,因为http服务器正在保留该端口,并且您的WebSocket将尝试绑定失败。但是如果发生这种情况,您应该在服务器上看到一个错误。

如果您想使用您的应用程序服务器端口,而不是启动一个不同的服务器,那么请遵循以下示例。

相关内容

最新更新