带有 Sails JS 和 React JS 的套接字

问题描述 投票:0回答:1

我有一个实时出价系统。在出价页面中,我们显示项目的基本价格和出价。当任何用户更新商品价格时,我想将该价格反映给所有打开出价页面的客户(无负载)。

我想当用户更新商品价格时从服务器向客户端发送消息。在客户端,当我收到服务器消息时,这将更新表数据。

配置/套接字

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();
      }
 },[])

上面的代码打印出以下内容.. React Page Console

我只是遵循教程...并且没有确切的概念... 谁能帮我解决这个问题吗

reactjs sockets sails.js
1个回答
0
投票

要进行广播,您需要先使用

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);
  };
}, []);

如果套接字连接到服务器,您将在控制台中看到this

© www.soinside.com 2019 - 2024. All rights reserved.