reactjs 已建立套接字连接,但无法发出服务器到客户端消息

cclgggtu  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(126)

我正在使用socket.io作为节点应用程序。应用程序内的套接字连接已建立,但数据无法从服务器发送到客户端。客户端和服务器位于不同的端口(3000和8080)

客户端:

客户端连接:

const socket = io.connect('http://localhost:8080', {
    rejectUnauthorized: false,
    transports: ['websocket', 'polling'],
    vary: origin,
    })
const sendMessage =()=>{
        socket.emit('SENDMSG',{message: 'hello'})
        joinRoom()
    }

    useEffect(()=>{
        socket.on("receive_msg", (data)=>{
            new Audio(order).play()
            console.log('data', data.ListOfOrders)
            setTableItems(data.ListOfOrders)
        });
    }, [socket])

    const joinRoom = ()=>{
        socket.emit('join_room', email)
    }

服务器端JS:

const http = require('http')
const server = http.createServer(app)

const { Server } = require('socket.io')
const io = new Server(server, {
    cors:{
        origin: `http://localhost:3000`,
        methods: ['GET', 'POST'],
        credentials: true,
        transports: ['websocket','polling'],
    },
    allowEIO3: true
});

//客户端连接时运行
一个三个三个一个
有没有人能帮我解决这个问题?如果你需要更多细节,请告诉我。如果有问题,我的接收器侧插座正在使用效果挂钩。

8hhllhi2

8hhllhi21#

要确保向所有连接的客户端发出事件,必须将io.to(searchRestaurant.email).emit('receive_msg',{ListOfOrders})行移动到服务器端的socket.on('join_room',...)回调中。这将确保向同一房间中的所有客户端发出事件
您的服务器端更新代码

io.on('connection', (socket) => {
  socket.on('join_room', (data) => {
    console.log(data);
    socket.join(data);
  });
});

app.post('/placeorder', async (req, res) => {
  try {
    const { ordersList, spiceLevel, name, id } = req.body;
    const searchRestaurant = await Restaurants.findOne({ shopName: name }).populate('orders');
    for (let order of ordersList) {
      let orderEntry = new Orders({
        qty: order.qty,
        food: order.itemName,
        tableNo: id,
        spiceLevel: spiceLevel,
        discount: order.discount,
        price: order.price,
        remarks: order.remarks
      });
      await orderEntry.save();
      searchRestaurant.orders.push(orderEntry._id);
      await searchRestaurant.save();
    }
    const ListOfOrders = searchRestaurant.orders;
    io.to(searchRestaurant.email).emit('receive_msg', { ListOfOrders }); 
    return res.status(200).send('your message');
  } catch (error) {
    return res.status(400).send('your message.');
  }
});

相关问题