Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

Node.js agent.maxSockets 속성 완벽 가이드 - 동시 소켓 연결 수 제어하기

agent.maxSockets 속성은 HTTP 에이전트가 각 오리진(origin)별로 동시에 열 수 있는 소켓의 최대 개수를 정의합니다. 기본값은 Infinity(무한대)로 설정되어 있으며, 이 속성은 Node.js의 'http' 모듈에 포함되어 있습니다.

문법(Syntax)

agent.maxSockets: number

매개변수(Parameters)

  • number – 에이전트가 유지할 수 있는 동시 소켓의 개수를 지정합니다. 기본값은 Infinity이며, 값을 설정하면 해당 오리진으로의 동시 연결 수가 제한됩니다.

예제(Example)

아래와 같이 maxSockets.js라는 이름의 파일을 생성하고 다음 코드를 복사해 붙여넣습니다. 파일 생성 후에는 아래 명령어를 실행하여 코드를 테스트할 수 있습니다.

node maxSockets.js

maxSockets.js

// agent.maxSockets 메서드 데모 예제

// http 모듈과 agentkeepalive 모듈 불러오기
const http = require('http');
const agent = require('agentkeepalive');

const keepaliveAgent = new agent({
    maxSockets: 100,
    maxFreeSockets: 10,
    timeout: 60000, // 활성 소켓 keepalive 시간: 60초
    freeSocketTimeout: 30000, // 유휴 소켓 keepalive 시간: 30초
});

const options = {
    host: 'tutorialspoint.com',
    port: 80,
    path: '/',
    method: 'GET',
    agent: keepaliveAgent,
};
console.log("Max free sockets: ",keepaliveAgent.maxSockets);
console.log('[%s] agent status changed: %j', Date(),
keepaliveAgent.getCurrentStatus());

실행 결과(Output)

C:\home\node>> node maxSockets.js
Max sockets: 100
[Fri Apr 30 2021 12:28:24 GMT+0530 (India Standard Time)] agent status
changed:
{"createSocketCount":0,"createSocketErrorCount":0,"closeSocketCount":0,"errorS
ocketCount":0,"timeoutSocketCount":0,"requestCount":0,"freeSockets":{},"socket
s":{},"requests":{}}

참고 사항

maxSockets 값이 무한대(Infinity)인 경우, 에이전트는 요청이 들어올 때마다 제한 없이 새로운 소켓을 생성합니다. 반면 특정 숫자로 설정하면, 해당 오리진에 대한 동시 연결 수가 제한되어 서버 과부하를 방지하고 리소스 사용을 효율적으로 관리할 수 있습니다. 높은 트래픽을 처리하는 애플리케이션에서는 maxFreeSockets, timeout 등의 옵션과 함께 적절히 조정하는 것이 좋습니다.