تمت ترجمة هذه الصفحة آليًا. النسخة الإنجليزية هي المصدر وقد تكون أكثر دقة أو أحدث. العرض بالإنجليزية

عميل المتصفح

يمكنك الاتصال من متصفح باستخدام واجهة WebSocket الأصلية. لا حاجة إلى مكتبة. توضّح هذه الصفحة عميلًا كاملًا يشترك، ويُبقي الاتصال حيًا، ويعيد الاتصال.


كيف يختلف عن عميل الخادم

  • المفتاح يوضع في عنوان URL. لا تستطيع المتصفحات ضبط الترويسات على WebSocket، لذا استخدم ?apiKey= بدلًا من ترويسة x-api-key.
  • لا يمكنك رؤية سبب رفض الاتصال. لا يعرض المتصفح حالة HTTP للاتصال المرفوض. يُغلق socket ببساطة بالرمز 1006 قبل أن يُفتح. المفتاح الخاطئ، والخطة التي لا تشمل WebSocket، وحدّ الاتصالات الممتلئ تبدو كلها متشابهة. توقّف بعد بضع محاولات فاشلة متتالية وافحص المفتاح والخطة في لوحة التحكم.
  • كل شيء آخر هو نفسه. أرسل رسالة الاشتراك، وأرسل ping كل 25 ثانية، وتعامل مع إطارات التحكّم، وأعِد الاتصال عند الحاجة. راجع دورة الحياة والحدود.

عناوين 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 ويرسل رسالة الاشتراك،
  • يرسل ping كل 25 ثانية ويعيد الاتصال عندما لا يصل pong خلال 60 ثانية،
  • يعيد الاتصال مع انتظار يزداد من ثانية واحدة إلى 30 ثانية، ويعيد ضبط الانتظار بعد pong أو مقال،
  • يتوقف بعد 5 اتصالات مرفوضة متتالية، وبعد VALIDATION_FAILED، وبعد إزاحة بالسبب connection_limit،
  • ينتظر ساعة واحدة بعد إزاحة بالسبب quota_exceeded،
  • يحذف الإطارات المكرّرة، وكذلك الدفعة الأولية بعد إعادة الاتصال،
  • يعيد الاتصال بعد 115 دقيقة، قبل حدّ الساعتين. هذا يترك فجوة قصيرة. املأها عبر REST إذا كنت تحتاج إلى كل مقال؛ راجع دورة الحياة والحدود.

يقرأ إطارات v3 وإطارات التحكّم بصيغة v2 التي يرسلها الخادم قبل الاشتراك الأول.

عميل المتصفح

WEBSOCKET
wss://wss.finlight.me
const 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، يُرسل قبل اشتراكك الأول.

راجع الإطارات للقائمة الكاملة ورموز الأخطاء.


ما التالي