initClient.ts 600 B

123456789101112131415161718
  1. import { DO_UPDATE, DONE_UPDATE, LOCAL_RELOAD_SOCKET_URL } from '../constant';
  2. import MessageInterpreter from '../interpreter';
  3. export default function initClient({ id, onUpdate }: { id: string; onUpdate: () => void }) {
  4. const ws = new WebSocket(LOCAL_RELOAD_SOCKET_URL);
  5. ws.onopen = () => {
  6. ws.addEventListener('message', event => {
  7. const message = MessageInterpreter.receive(String(event.data));
  8. if (message.type === DO_UPDATE && message.id === id) {
  9. onUpdate();
  10. ws.send(MessageInterpreter.send({ type: DONE_UPDATE }));
  11. return;
  12. }
  13. });
  14. };
  15. }