웹소켓 (WebSocket)
- 양방향 통신 프로토콜
- WebSocket 프로토콜로 연결하기 위해서는 websocket handshake 가 필요하다.
URI 스키마는 ws:// 를 사용하며 암호화 소켓은 wss:// 을 사용한다.
- WebSocket 사용을 위해서는 HTTP 통신을 통해 Upgrade Request 를 보내야 한다.
cf) 기존 HTTP 프로토콜의 양방향 통신 방법
- Polling
- Long Poling
- Streaming
참고
Adamrehn/websocket-server-demo
- 코드
- 코드
- Q&A
Q: I did websocket client using service worker but after 5 minutes service worker getting inactive and disconnected from the server. Is there any way to keep service worker active?
A: Incorporating keepalive into the service worker might solve the problem.
keepAlive();
function keepAlive() {
console.log("keepAlive");
setTimeout(keepAlive, 1000);
}
Q: doesn't work but keeping the port that service worker uses open looks like a solution. At least for now
A:
keepAlive();
chrome.runtime.onConnect.addListener(port => {
if (port.name === 'keepAlive') {
lifeline = port;
setTimeout(keepAliveForced, 295e3); // 5 minutes minus 5 seconds
port.onDisconnect.addListener(keepAliveForced);
}
});
function keepAliveForced() {
lifeline?.disconnect();
lifeline = null;
keepAlive();
}
async function keepAlive() {
if (lifeline) return;
for (const tab of await chrome.tabs.query({ url: '*://*/*' })) {
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => chrome.runtime.connect({ name: 'keepAlive' }),
// `function` will become `func` in Chrome 93+
});
chrome.tabs.onUpdated.removeListener(retryOnTabUpdate);
return;
} catch (e) {}
}
chrome.tabs.onUpdated.addListener(retryOnTabUpdate);
}
async function retryOnTabUpdate(tabId, info, tab) {
if (info.url && /^(file|https?):/.test(info.url)) {
keepAlive();
}
}
'배움의공간(學) > 기타' 카테고리의 다른 글
async 와 await (0) | 2023.06.28 |
---|---|
두바이-튀르키예 여행 (0) | 2023.05.15 |
[GCA] Introducing Google Cloud (0) | 2023.02.10 |
핸드폰으로 밤하늘 별 촬영법 (0) | 2023.02.07 |
Stack overflow survey (0) | 2023.01.02 |
댓글