Post

[HTTP] 04. 추가 프로토콜 - 10장. 롱 폴링

[HTTP] 04. 추가 프로토콜 - 10장. 롱 폴링

04. 추가 프로토콜


10장. 롱 폴링

10-1. 구조

  • 서버에 요청하고 데이터가 올 때까지 대기한다. (새로운 데이터가 있을 때까지 연결을 지속한다.)
  • 서버 자원을 낭비할 수 있다.
  • 비유: 새로운 소식이 있나요? 잠깐만 기다려 보세요.

10-2. 서버 구현

  • 클라이언트 대기열 준비
  • 채팅 메시지 조회 기능
  • 채팅 메시지 추가 기능
1
2
3
4
5
$ curl http://localhost:3000/longPoll -v

$ curl http://localhost:3000/update ^
--header "Content-Type: application:json" ^
--data "{\"text\": \"hello\"}" -v

10-3. 클라이언트 구현

  • 지속적으로 요청 생성
  • 수신한 메시지를 출력

10-4. 중간 정리

  • HTTP 연결을 유지하기 위해 응답을 지연하는 기법
  • 특징: 실시간성
  • 주의사항: 서버 자원을 낭비할 수 있다.

참고


예제

파일구조

  • /ch10
    • public
      • favicon.ico
      • index.html
      • script.js
    • shared
      • message.js
      • serve-static.js
    • server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const longPollServer = async () => {
  const response = await fetch('/longPoll');

  if (response.status == 408) {
    longPollServer(); // 재요청
    return;
  }

  const message = await response.json();
  render(message);

  longPollServer(); // 재요청
};

const render = (message) => {
  const messageElement = document.createElement('div');
  const { text } = message;
  const timestamp = new Date(message.timestamp).toLocaleTimeString();
  messageElement.textContent = `${text} (${timestamp})`;
  document.body.appendChild(messageElement);
};

const init = () => {
  longPollServer();
};

document.addEventListener('DOMContentLoaded', init);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Message {
  constructor(text) {
    this.text = text;
    this.timestamp = Date.now();
  }

  toString() {
    return JSON.stringify({
      text: this.text,
      timestamp: this.timestamp,
    });
  }
}

module.exports = Message;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const fs = require('fs');
const path = require('path');

const serveStatic = (root) => {
  return (req, res) => {
    const filepath = path.join(root, req.url === '/' ? '/index.html' : req.url);

    fs.readFile(filepath, (err, data) => {
      if (err) {
        if (err.code === 'ENOENT') {
          res.statusCode = 404;
          res.write('Not Found\n');
          res.end();
          return;
        }

        res.statusCode = 500;
        res.write('Internal Server Error\n');
        res.end();
        return;
      }

      const ext = path.extname(filepath).toLowerCase();
      let contentType = 'text/html';
      switch (ext) {
        case '.html':
          contentType = 'text/html';
          break;
        case '.js':
          contentType = 'text/javascript';
          break;
        case '.css':
          contentType = 'text/css';
          break;
        case '.png':
          contentType = 'image/png';
          break;
        case '.json':
          contentType = 'application/json';
          break;
        case '.otf':
          contentType = 'font/otf';
          break;
        default:
          contentType = 'application/octet-stream';
      }
      res.setHeader('Content-Type', contentType);

      res.write(data);
      res.end();
    });
  };
};

module.exports = serveStatic;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const http = require('http');
const path = require('path');
const static = require('./shared/serve-static');
const Message = require('./shared/message');

let waitingClients = []; // 대기중인 클라이언트의 배열
let message = null;

const longPoll = (req, res) => {
  const WAITING_TIMES_MS = 10000;

  if (!message) {
    waitingClients.push(res);

    res.setTimeout(WAITING_TIMES_MS, () => {
      res.statusCode = 408;
      res.end();
    });

    return;
  }

  if (res.headersSent) {
    res.setHeader('Content-Type', 'application/json');
    res.write(`${message}\n`);
    res.end;
  }

  message = null;
};

const update = (req, res) => {
  let body = '';
  req.on('data', (chunk) => {
    body = body + chunk.toString();
  });

  req.on('end', () => {
    const { text } = JSON.parse(body);

    if (!text) {
      res.statusCode = 400;
      res.setHeader('Content-Type', 'application/json');
      res.write(JSON.stringify({ error: 'text 필드를 채워주세요' }));
      res.end();
      return;
    }

    message = new Message(text);

    for (const waitingClient of waitingClients) {
      if (!waitingClient.headersSent) {
        waitingClient.setHeader('content-type', 'application/json');
        waitingClient.write(`${message}`);
        waitingClient.end();
      }
    }

    if (!res.headersSent) {
      res.setHeader('Content-Type', 'application/json');
      res.write(`${message}`);
      res.end();
    }

    message = null;
    waitingClients = [];
  });
};

const handler = (req, res) => {
  const { pathname } = new URL(req.url, `http://${req.headers.host}`);

  if (pathname === '/longPoll') return longPoll(req, res);
  if (pathname === '/update') return update(req, res);

  static(path.join(__dirname, 'public'))(req, res);
};

const server = http.createServer(handler);
server.listen(3000, () => console.log('server is running ::3000'));
This post is licensed under CC BY 4.0 by the author.

Trending Tags