[英]Node.js - WebSocket only works when refreshing the page
I am trying to communicate with the websocket in Node.js.我正在尝试与 Node.js 中的 websocket 通信。 It works when the page is first opened but I cannot receive messages without refreshing the page later.它在第一次打开页面时工作,但我无法在不刷新页面的情况下接收消息。
HTML PAGES WEBSOCKET CODE: HTML 页面 WEBSOCKET 代码:
var ws ;
function init() {
ws = new WebSocket('ws://localhost:40510');
ws.onopen = function () {
ws.send('test')
}
ws.onmessage = function (ev) {
console.log(ev)
}
}
window.addEventListener("load", init, false);
SERVER SIDE CODE:服务器端代码:
app.get('/sayfayiYenile', function (req, res) {
wss.on('connection', function connection(ws) {
ws.send('abc');
});
res.end('test')
});
CHROME CONSOLE:铬控制台:
MessageEvent {isTrusted: true, data: "abc", origin: "ws://localhost:40510", lastEventId: "", source: null, …}
When I press the button, it goes into the '/sayfayiYenile' post method on the server side but does not send the message.当我按下按钮时,它进入服务器端的“/sayfayiYenile” post 方法,但不发送消息。 Then I refresh the HTML page and send the message.然后我刷新 HTML 页面并发送消息。
Your .get
method isn't emitting a message, it's wrapping the .on("connection")
websocket logic instead.您的.get
方法没有发出消息,而是包装了.on("connection")
websocket 逻辑。 You should place the ws.on
functionality outside the .get
and implement logic to send a message to a specific connection.您应该将ws.on
功能放在.get
之外,并实现向特定连接发送消息的逻辑。
Example:例子:
const connections = [];
wss.on('connection', function connection(ws) {
ws.send("Welcome...");
// Store the list of connections for later use
connections.push(ws);
});
app.get('/sayfayiYenile', function (req, res) {
// Iterate over the current connected clients and send a message
// @todo implement logic here to filter out specific connections
connections.forEach(function(connection) {
connection.send('abc');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.