브라우저 클라이언트
브라우저에서 네이티브 WebSocket API로 연결할 수 있습니다. 라이브러리는 필요 없습니다. 이 페이지에서는 구독하고, 연결을 유지하고, 다시 연결하는 완전한 클라이언트를 보여 줍니다.
웹 페이지에 있는 키는 페이지를 여는 모든 사람에게 보입니다. 브라우저는 폐기할 수 있는 키로 짧은 테스트와 내부 도구에만 쓰세요. 공개 사이트라면 키를 비밀로 지키는 자체 서버에서 연결하고 기사를 사용자에게 전달하세요.
서버 클라이언트와 다른 점
- 키는 URL에 넣습니다. 브라우저는 WebSocket에 헤더를 설정할 수 없으므로
x-api-key헤더 대신?apiKey=를 씁니다. - 연결이 거부된 이유를 볼 수 없습니다. 브라우저는 거부된 연결의 HTTP 상태를 보여 주지 않습니다. 소켓은 열리기 전에 코드
1006으로 닫힐 뿐입니다. 잘못된 키, WebSocket이 없는 요금제, 가득 찬 연결 제한이 모두 똑같아 보입니다. 연속으로 몇 번 실패하면 멈추고 대시보드에서 키와 요금제를 확인하세요. - 나머지는 모두 같습니다. 구독 메시지를 보내고, 25초마다 ping을 보내고, 제어 프레임을 처리하고, 필요하면 다시 연결하세요. 수명 주기 및 제한을 참조하세요.
연결 URL
| 스트림 | URL |
|---|---|
| 보강 | wss://wss.finlight.me?apiKey=YOUR_API_KEY |
| 원시 | wss://wss.finlight.me/raw?apiKey=YOUR_API_KEY |
선택적 쿼리 매개변수: takeover=true는 제한에 도달했을 때 가장 오래 응답 없는 연결을 대체하고, clientVersion=...은 클라이언트에 레이블을 붙입니다. 값은 URL 인코딩하세요. 연결을 참조하세요.
WEBSOCKET브라우저
완전한 예시
이 클라이언트는:
- URL의 키로 연결하고 구독 메시지를 보냅니다,
- 25초마다 ping을 보내고 60초 동안 pong이 없으면 다시 연결합니다,
- 1초에서 30초까지 늘어나는 대기로 다시 연결하고, pong이나 기사가 온 뒤 대기를 되돌립니다,
- 연속 5번의 연결 거부,
VALIDATION_FAILED,connection_limit선점 후에는 멈춥니다, quota_exceeded선점 후에는 한 시간 기다립니다,- 재연결 후의 초기 푸시를 포함해 중복 프레임을 버립니다,
- 2시간 제한 전인 115분 후에 다시 연결합니다. 짧은 빈틈이 생깁니다. 모든 기사가 필요하면 REST로 채우세요. 수명 주기 및 제한을 참조하세요.
v3 프레임과 서버가 첫 구독 전에 보내는 v2 제어 프레임을 모두 읽습니다.
브라우저 클라이언트
WEBSOCKET
wss://wss.finlight.meconst API_KEY = 'YOUR_API_KEY' // tests only, see the note above
const BASE_URL = 'wss://wss.finlight.me' // raw stream: 'wss://wss.finlight.me/raw'
const SUBSCRIBE = {
payloadVersion: 3,
query: 'ticker:AMD',
language: 'en',
include: ['companies', 'events'], // leave out on the raw stream
includeUpdates: true,
clientNonce: crypto.randomUUID(),
}
function startStream({ onArticle, onStatus = console.log }) {
let ws
let pingTimer
let watchdog
let rotateTimer
let delay = 1000
let refusedInARow = 0
let stopped = false
const seen = new Set()
const resetWatchdog = () => {
clearTimeout(watchdog)
watchdog = setTimeout(() => ws.close(4000, 'no pong'), 60_000)
}
const stop = (why) => {
stopped = true
onStatus(`stopped: ${why}`)
ws?.close(1000)
}
const scheduleReconnect = (waitMs) => {
onStatus(`reconnecting in ${Math.round(waitMs / 1000)} s`)
setTimeout(connect, waitMs)
}
function connect() {
if (stopped) return
let opened = false
let nextWait = null // set by frames that need a special wait
ws = new WebSocket(`${BASE_URL}?apiKey=${encodeURIComponent(API_KEY)}`)
ws.onopen = () => {
opened = true
refusedInARow = 0
ws.send(JSON.stringify(SUBSCRIBE))
pingTimer = setInterval(() => ws.send(JSON.stringify({ action: 'ping', t: Date.now() })), 25_000)
rotateTimer = setTimeout(() => {
nextWait = 0
ws.close(1000, 'rotate')
}, 115 * 60_000)
resetWatchdog()
}
ws.onmessage = (message) => {
const frame = JSON.parse(message.data)
const name = frame.event ?? frame.action // v2 control frames use "action"
const data = frame.data ?? frame
switch (name) {
case 'article.created':
case 'article.updated': {
delay = 1000
resetWatchdog()
const key = `${name}|${data.id}|${JSON.stringify(data)}`
if (seen.has(key)) return
seen.add(key)
if (seen.size > 5000) seen.delete(seen.values().next().value)
onArticle(name, data)
break
}
case 'connection.pong':
case 'pong':
delay = 1000
resetWatchdog()
break
case 'connection.admitted':
case 'admit':
onStatus(`admitted, lease ${data.leaseId}`)
break
case 'connection.preempted':
case 'preempted':
if (data.reason === 'connection_limit') stop('another connection took over')
else nextWait = 60 * 60_000 // quota_exceeded: try again in one hour
break
case 'connection.error':
if (data.code === 'VALIDATION_FAILED') stop(`subscribe rejected: ${JSON.stringify(data.details)}`)
else onStatus(`server error ${data.code}: ${data.message}`)
break
default:
// "error" in v2 form, or an event this client does not know yet
onStatus(`ignored frame ${name}`)
}
}
ws.onclose = (event) => {
clearInterval(pingTimer)
clearTimeout(watchdog)
clearTimeout(rotateTimer)
if (stopped) return
if (!opened && ++refusedInARow >= 5) {
stop('connection refused 5 times: check the API key and your plan')
return
}
if (event.code === 1008) {
stop('closed by the server with code 1008')
return
}
const wait = nextWait ?? delay
delay = Math.min(delay * 2, 30_000)
scheduleReconnect(wait)
}
}
connect()
return { close: () => stop('closed by you') }
}
// Usage
const stream = startStream({
onArticle: (event, article) => console.log(event, article.id, article.title),
})
// later: stream.close()
보게 될 메시지
| 프레임 | 의미 |
|---|---|
connection.admitted | 첫 구독이 도착했습니다. 서버가 구독을 확인하기 전에 보냅니다. |
article.created | 새로 일치하는 기사입니다. 구독 직후의 첫 기사는 이미 있는 가장 최근의 일치 기사입니다. |
article.updated | 일치하는 기사의 변경입니다. includeUpdates: true일 때만 옵니다. |
connection.pong | ping에 대한 응답입니다. |
connection.preempted | 서버가 이 연결을 닫습니다. reason을 확인하세요. |
connection.error | 메시지에 문제가 있습니다. code를 확인하세요. |
{"action": ...} | 첫 구독 전에 보내는 v2 형식의 제어 프레임입니다. |
전체 목록과 오류 코드는 프레임을 참조하세요.
다음 단계
- 구독: 모든 구독 필드.
- 원시 스트림: 더 빠른 기본 골격 스트림.
- 수명 주기 및 제한: ping, 교체, 할당량, 빈틈 채우기.