모든 이벤트에 호출되는 리스너 : 디버깅용

socket.onAny((eventName, ...args) => {
  console.log(eventName); // 'hello'
  console.log(args); // [ 1, '2', { 3: '4', 5: ArrayBuffer (1) [ 6 ] } ]
});

메세지를 전송할때

  1. 프론트 메세지가 전송 이벤트를 발생

    form.addEventListener('submit', (e) => {
      e.preventDefault();
      if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    });
    //chat message이벤트가 발생할때마다 화면에 메세지를 띄워줌
    socket.on('chat message', (msg) => {
      const item = document.createElement('li');
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
    
  2. 백엔드

    //chat message가 발생할때 다른 사용자들에게 브로드캐스트 한다.
    io.on('connection', (socket) => {
        socket.on('chat message', async (msg) => {
          let result;
          try {
            // store the message in the database
            result = await db.run('INSERT INTO messages (content) VALUES (?)', msg);
          } catch (e) {
            // TODO handle the failure
            return;
          }
          // include the offset with the message
          io.emit('chat message', msg, result.lastID);
        });
      });
    

    https://socket.io/docs/v4/tutorial/step-7

소켓에 데이터를 담아 전송하기

  1. 전송하기

    socket.emit('hello', 1, '2', { 3: '4', 5: Uint8Array.from([6]) });
    
  2. 받기

    socket.on('hello', (arg1, arg2, arg3) => {
      console.log(arg1); // 1
      console.log(arg2); // '2'
      console.log(arg3); // { 3: '4', 5: <Buffer 06> }
    });
    

에러처리

  1. Client

    socket.timeout(5000).emit('request', { foo: 'bar' }, 'baz', (err, response) => {
      if (err) {
        // the server did not acknowledge the event in the given delay
      } else {
        console.log(response.status); // 'ok'
      }
    });
    
  2. Server

    io.on('connection', (socket) => {
      socket.on('request', (arg1, arg2, callback) => {
        console.log(arg1); // { foo: 'bar' }
        console.log(arg2); // 'baz'
        callback({
          status: 'ok'
        });
      });
    });
    

이벤트 발생을 지연시키고 싶을때 setTimout → emitWithAck

try {
  const response = socket.timeout(5000).emitWithAck('request', { foo: 'bar' }, 'baz');
  console.log(response.status); // 'ok'
} catch (e) {
  // the server did not acknowledge the event in the given delay
}