我有一个实时出价系统。在出价页面中,我们显示项目的基本价格和出价。当任何用户更新商品价格时,我想将该价格反映给所有打开出价页面的客户(无负载)。
我想当用户更新商品价格时从服务器向客户端发送消息。在客户端,当我收到服务器消息时,这将更新表数据。
配置/套接字
transports: ['polling', 'websocket'],
服务器端 - 在 BidUpdateController [http://localhost:7039]
sails.io.on("connection", (socket) => {
console.log("SOCKET ID : "+socket.id);
sails.sockets.broadcast('bidUpdate',{ greeting: 'UPDATED!' });
socket.on('disconnect', () => { // Is this necessary..?
console.log('User disconnected');
});
})
上面的代码在我的控制台中打印套接字 ID... 套接字 ID:wjMGczPrXtx5UpOrBBN3
客户端 - 在 React Bid List 页面中 [http://localhost:3637]
import io from 'socket.io-client';
React.useEffect(() => {
let connectionOptions = {
"force new connection" : true,
"reconnectionAttempts": "Infinity",
"timeout" : 20000,
"transports" : ['polling', 'websocket']
};
const socket = io.connect('http://localhost:7039',connectionOptions);
console.log("SOCKET CONNECTION : "+socket.connected); // This return False
socket.on('bidUpdate', (data) => { //This do nothing
console.log("Response"+ data.greeting);
//if i receive data then i will call function that update table data..
});
return () => {
socket.disconnect();
}
},[])
我只是遵循教程...并且没有确切的概念... 谁能帮我解决这个问题吗
要进行广播,您需要先使用
sails.sockets.join()
加入房间。
要在不加入房间的情况下向所有套接字广播消息,您只需使用 sails.sockets.blast()
即可。 文档链接
在 BidUpdateController 中,您可以简单地
sails.sockets.blast('bidUpdate',{ greeting: 'UPDATED!' });
在反应投标列表页面
import socketIOClient from "socket.io-client";
import sailsIOClient from "sails.io.js";
React.useEffect(() => {
// Create an instance of the io socket
let io;
if (socketIOClient.sails) {
io = socketIOClient;
} else {
io = sailsIOClient(socketIOClient);
}
io.sails.url = "http://localhost:7039"; // Set the server URL
io.socket.on("connect", function onConnect() {
console.log("This socket is now connected to the Sails server!");
});
const bidUpdateHandler = (data) => {
console.log("Received response: " + data.greeting);
};
// Attach the 'bidUpdate' event listener
io.socket.on('bidUpdate', bidUpdateHandler);
// Clean up the event listener when the component unmounts
return () => {
io.socket.off('bidUpdate', bidUpdateHandler);
};
}, []);