How to generate the socket emit events under API's calls

蓝咒 提交于 2020-02-05 12:03:05

问题


I need the help/support/guidance regarding the Socket.io On My server page i.e app.js, I initialized the Socket and it works fine. Now I want to call the emit function to some other page. But I did not get the event from another page because the event generated under connection. I will share the pseudo code by which you can get some idea about app.js page

const io = require('socket.io');
  const server = io.listen(3003);
  const triggerEvent = (socket) => {
    return socket.emit('event-trigger', true);
  }
  server.on('connection', function (socket) {
    triggerEvent(socket);
  });

I also tried to use Module.exports triggerEvent Function and get that function other pages My HTML page where I am opening and testing the Socket Connection test.html:

<html>

<head>
  <title>Socket io client</title>
  <script src="http://localhost:3003/socket.io/socket.io.js"></script>
  <script>
    var socket = io("http://localhost:3003");
    // use your socket
    socket.on("event-trigger", (message) => {
      // do something with the message.
      alert(message)
      console.log(message)
    })
  </script>
</head>

<body>
</body>

</html>

So currently it works fine. If I open the HTML Page then alert generated by socket server. Also user connected message print on my server console.

Now I have multiple routes and under that multiple files where API functionality is written. So let's say Some routes folder I have handle.js file. Under that file let's say I have an API named as localhost:3000/likepost. So on this API when a user like is posted and 200 success response is sent back to Frontend Server, then just after I want to trigger the event i.e socket .emit('event-trigger', true); and this event will send Frontend the event fired request, so Frontend will show some notification like someone liked your post is rendering on platform something like that. Please provide me some guidance for that. Any help or suggestion is really appreciated for that.


回答1:


Your socket connection reference is not attached to the emit function, it should be inside your "connection" (server.on('connection')) callback function Reference below :

  const io = require('socket.io');
  const server = io.listen(3003);

  server.on('connection', function (socket) {      
    socket.emit('event-trigger', true);      
  });


来源:https://stackoverflow.com/questions/59138579/how-to-generate-the-socket-emit-events-under-apis-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!