简体   繁体   English

套接字io延迟一个事件

[英]Socket io delay one event

I have connected socket io to Webhook and it succeeds.我已将 socket io 连接到 Webhook,它成功了。 It can get information and can express But I'm stuck with one problem.它可以获取信息并可以表达但我遇到了一个问题。 When the desired value is displayed on the client-side, the response is delayed.当客户端显示所需的值时,响应会延迟。 For example, when the server-side detects an event will show on console.log();例如,当服务器端检测到一个事件时会显示在console.log()上; But it won't show on the client-side.但它不会显示在客户端。 But when the server-side detects the event again (second time) The value saved the first time is sent to the client-side, and if the server detects the event again (third time) The second event value is sent to the client-side, which means it will delay the event one time.但是当服务器端再次(第二次)检测到事件时,将第一次保存的值发送给客户端,如果服务器再次(第三次)检测到事件,则将第二次事件值发送给客户端——侧,这意味着它将延迟事件一次。 How can I fix this incident?我该如何解决这个事件?

 // Server const app = require('express')(); const http = require('http').createServer(app); const io = require('socket.io', { transports: ['websocket', 'polling'] })(http, { cors: { origin:'*' } }); const bodyParser = require("body-parser"); PORT = 8080; io.on('connection', socket => { app.use(bodyParser.json()); app.post('/api', (req, res) => { let x = req.body[0]; let dates = x.created_date; let name = x.name; let watchlist = x.watchlist[Object]; if (watchlist == "Matched"){ console.log("Date :", dates) console.log("Name :", name) io.emit('FromAPI', dates, name); } else { console.log("Unmatch") } res.status(200).end("Successfully"); }); console.log('Socket connected'); socket.on('disconnect', () => { console.log('Socket disconnected')}); }); http.listen(PORT, () => { console.log(`Server : http://localhost: ${PORT}`); });

 // Client import { useEffect, useState } from 'react'; import io from 'socket.io-client'; const socket = io("http://localhost:8080", { transports: ['websocket', 'polling'] }); export default function App() { const [date, setDate] = useState(''); const [name, setName] = useState(''); const [hook_event, setHook_event] = useState([ { "date": date, "name": name}, { "date": date, "name": name} ]); useEffect(() => { socket.on('FromAPI', (date, name) => { setDate(date); setName(name); hook_event.unshift({"date": date, "name": name}); hook_event.pop(); }) }, []; return ( <> <p>Date : {hook_event[0].date} and {hook_event[0].name}</p> <p>Date : {hook_event[1].date} and {hook_event[1].name}</p> </> ); };

I think I found the problem.我想我发现了问题。

    const [countState, setCountState] = useState() 

    useEffect(() => {
    socket.on('FromAPI', (date, name) => {
      setDate(date);
      setName(name);

      hook_event.unshift({"date": date, "name": name});
      hook_event.pop();
      setCountState(hook_event[0])
    })
    }, [setCountState]; // update setCountState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM