jongpak / dev-tip

My Dev tips
1 stars 0 forks source link

node request 라이브러리의 타임아웃에 대하여 #5

Open jongpak opened 4 years ago

jongpak commented 4 years ago

파이썬 서버 예제

#-*- coding:utf-8 -*-

import socket
import select
import time

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

serverSocket.bind(('127.0.0.1', 8080))
serverSocket.listen(1)

while True:
    readSocketList, writeSocketList, exceptSocketList = select.select([serverSocket], [], [])

    # 접속이 많아서 accept 지연 시뮬레이션
    time.sleep(0.1)
    clientSocket, addr = serverSocket.accept()
    print('CONNECT: ', addr)

    try:
        # 서버 처리가 지연되어 write 지연 시뮬레이션
        time.sleep(0.1)
        clientSocket.sendall('HTTP/1.0 200 OK\r\nContent-Length: 2\r\n\r\n'.encode())
        time.sleep(0.2)
        clientSocket.sendall('OK'.encode())
        print('FINISH - OK')
    except socket.error:
        print('FINISH - ERROR')
    finally:
        clientSocket.close()

serverSocket.close()

노드 클라이언트 예제

const request = require('request');

const start = (new Date()).getTime();
request('http://127.0.0.1:8080', { timeout: 250, time: true }, function(error, response) {
    const end = (new Date()).getTime();
    if (error) {
        console.log('ERROR = ' + error.message);
    } else {
        console.log(response.timings);
    }
    console.log('END = ' + (end - start));
});
{
    "dependencies": {
        "request": "2.88.0",
        "request-promise": "4.2.5"
    }
}

결과

$ node client.js 
{
  socket: 4.861184000000009,
  connect: 6.237954000000002,
  response: 211.363835,
  end: 416.17645699999997,
  lookup: 4.861184000000009
}
END = 420

이유