Sha*_*ika 5 javascript node.js reactjs stackexchange-api react-native
我想回答新的javascript,react,react-native和node问题。那么,我如何知道用户在这些领域提出的新问题?
打开与的Websocket连接wss://qa.sockets.stackexchange.com/,然后将消息发送到您要关注的标记1-questions-newest-tag-TAG所在的位置TAG。这是一个直播片段:
const socket = new WebSocket('wss://qa.sockets.stackexchange.com/');
socket.onopen = () => {
socket.send('1-questions-newest-tag-javascript');
socket.send('1-questions-newest-tag-react');
socket.send('1-questions-newest-tag-react-native');
socket.send('1-questions-newest-tag-node.js');
console.log('Listening...');
};
const seenQuestions = new Set();
socket.onmessage = ({ data }) => {
const obj = JSON.parse(data);
if (obj.action === 'hb') {
socket.send('pong');
} else {
const { id, body } = JSON.parse(obj.data);
if (seenQuestions.has(id)) {
// Duplicate question, a message for it has already been handled:
return;
}
seenQuestions.add(id);
console.log('New question:', id);
document.body.insertAdjacentHTML('beforeend', body);
}
};
socket.onerror = console.error; // just in caseRun Code Online (Sandbox Code Playgroud)
<!-- Makes the inserted questions look a bit prettier: -->
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/primary.css?v=d385c34dc2d7">Run Code Online (Sandbox Code Playgroud)
您确实需要侦听hb消息并回复它,以便StackExchange知道保持连接活动。
请注意,套接字将针对正在侦听的每个标签发送给定问题的数据。例如,如果某些东西同时被Javascript和React标记,您将收到两次有关该消息的消息。
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |