浏览器客户端
您可以在浏览器中用原生 WebSocket API 连接,不需要任何库。本页展示一个完整的客户端,它会订阅、保持连接并重新连接。
网页中的密钥对每个打开网页的人都可见。只在短时间测试和内部工具中使用浏览器,并使用可以吊销的密钥。对于公开网站,请从您自己的服务器连接,由服务器保管密钥,再把文章转发给您的用户。
与服务器客户端的区别
- 密钥放在 URL 中。 浏览器无法在 WebSocket 上设置标头,所以请使用
?apiKey=,而不是x-api-key标头。 - 您看不到连接被拒绝的原因。 浏览器不会显示被拒绝连接的 HTTP 状态码。socket 只是在打开之前以代码
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 编码。请参阅连接。
WEBSOCKETBrowser
完整示例
这个客户端:
- 使用 URL 中的密钥连接,并发送订阅消息;
- 每 25 秒发送一次 ping,60 秒内没有收到 pong 就重新连接;
- 以从 1 秒增长到 30 秒的等待时间重新连接,并在收到 pong 或文章后重置等待时间;
- 在连续 5 次连接被拒绝、收到
VALIDATION_FAILED或因connection_limit被抢占后停止; - 因
quota_exceeded被抢占后等待一小时; - 丢弃重复的帧,包括重连后的初始推送;
- 在 115 分钟后、2 小时上限之前重新连接。这会留下一个短暂的缺口。如果您需要每一篇文章,请通过 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 形式的控制帧,在您第一次订阅之前发送。 |
完整列表和错误代码请参阅帧。