Stack Exchange如何检查新帖子/评论



我一直在看"网络"部分,查看Stack Overflow上的新帖子和活跃帖子的活动情况。

我期望看到定期的网络活动来检查页面上更新元素的脚本(如新的评论或回答张贴)-但似乎没有一个!

我刚刚实现了一个周期性的"心跳"在我的网站上的一些页面

Stack Overflow是否实现了某种"push"?查看新帖子?

使用websockets

在页面加载时,站点连接到wss://qa.sockets.stackexchange.com/ websocket并向其发送<site_id>-question-<question_id>消息(例如1-question-14384446),因此订阅问题事件(新答案,新评论,帖子删除,分数更改等)。

下面是一个JavaScript示例。为了测试它是否有效,你可以在你的问题或答案下面添加一个注释:

const socket = new WebSocket('wss://qa.sockets.stackexchange.com/');
socket.onopen = () => {
  socket.send('1-question-14384446'); // subscribe to question events
  console.log('Listening for new comments...');
};
socket.onmessage = ({ data }) => {
  const obj = JSON.parse(data);
  // sent every 5 minutes to check if connection is alive
  if (obj.action === 'hb') {
    socket.send('pong');
    return;
  }
  const { a: type, commentid } = JSON.parse(obj.data);
  if (type !== 'comment-add') return; // not a comment
  console.log('New comment with id', commentid);
};
socket.onerror = console.error; // just in case

参考:

  • 栈交换WebSockets是如何工作的?你能发给他们的所有选项是什么?
  • full.en.js文件-参见subscribeToQuestion(sid, pid)函数

最新更新