centrifuge5.0.1版本请求websocket实例

2023-12-26 18:54:55

目录

一、安转

二、快速开始?

三、实例开始


centrifuge提供了一个客户端,可使用纯 WebSocket 或一种替代传输(HTTP 流、SSE/EventSource、实验性 WebTransport)从 Web 浏览器、ReactNative 或 NodeJS 环境连接到Centrifugo或任何基于 Centrifuge 的服务器。

一、安转

centrifuge可以通过pnpm安装:

pnpm add centrifuge

然后在你的项目中:

import { Centrifuge } from 'centrifuge';
在浏览器中,您可以从CDN导入SDK(替换5.0.0为您要使用的具体版本号,请参阅releases):
<script src="https://unpkg.com/centrifuge@5.0.0/dist/centrifuge.js"></script>
另请参阅cdnjs 上的 centcent-js。请注意,centrifuge-js浏览器构建目标ES6默认情况下,库仅适用于 JSON,如果您想发送二进制有效负载,请转到Protobuf 支持部分以了解如何导入具有 Protobuf 支持的客户端。

二、快速开始?

基本用法示例可能如下所示:

// Use WebSocket transport endpoint.
const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');

// Allocate Subscription to a channel.
const sub = centrifuge.newSubscription('news');

// React on `news` channel real-time publications.
sub.on('publication', function(ctx) {
    console.log(ctx.data);
});

// Trigger subscribe process.
sub.subscribe();

// Trigger actual connection establishement.
centrifuge.connect();

请注意,我们显式调用.connect()方法来启动与服务器的连接建立,以及.subscribe()将订阅移动到状态的方法(在与服务器建立连接后subsribing应立即转换为状态)。和调用subscribed的顺序在这里实际上并不重要。.connect().subscribe

Centrifugeobject 和Subscriptionobject 都是EventEmitter的实例。下面我们将详细描述可以曝光的事件。

三、实例开始

<!DOCTYPE html>
<html lang="cn">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>socktest</title>
    <script src="./centrifuge.js"></script>
  </head>
  <body>
    <button onclick="handleSubscribeWebsocket()">订阅</button>
    <button onclick="unsubscribe()">取消订阅</button>
    <button onclick="presence()">获取订阅端的信息</button>
    <button onclick="history()">拉取历史记录</button>
    <button onclick="closeit()">断开连接</button>
    <a href="https://github.com/centrifugal/centrifuge-js" target="_blank"
      >参见官网</a
    >
  </body>
</html>
<script>
  console.log(Centrifuge);
  // Subscribe to the channel
  let subscription, centrifuge;
  const statistics = 'statistics';
  const handleGetWebsocket = async () => {
    try {
      const res = await fetch(
        'http://192.168.1.192:7089/api/v1/websocket_token'
      );
      const data = await res.json();
      console.log(
        '🚀 ~ file: hello.html:23 ~ handleGetWebsocket ~ data:',
        data
      );
      return data.data;
    } catch (error) {}
  };
  async function handleSubscriptionToken(path, token) {
    try {
      // ctx argument has a channel.
      const res = await fetch(
        `http://192.168.1.192:7089/api/v1/websocket_token/${path}`,
        {
          method: 'Get',
          headers: new Headers({
            'Content-Type': 'application/json',
            Authorization: token
          })
        }
      );
      const data = await res.json();
      return data.data.token;
    } catch (error) {}
  }

  const handleSubscribeWebsocket = async () => {
    const socketData = await handleGetWebsocket();
    console.log(
      '🚀 ~ file: hello.html:58 ~ handleSubscribeWebsocket ~ socketData:',
      socketData
    );
    centrifuge = new Centrifuge(socketData.url, {
      token: socketData.token
    });
    centrifuge.on('connecting', function (ctx) {
      console.log('🚀 ~ file: HomeCounter.tsx:52 ~ ctx:', ctx);
      // do whatever you need in case of connecting to a server
    });
    centrifuge.on('connected', function (ctx) {
      console.log('🚀 ~ file: HomeCounter.tsx:45 ~ ctx:', ctx);
      // now client connected to Centrifugo and authenticated.
    });
    centrifuge.on('error', function (ctx) {
      console.log(ctx);
    });
    centrifuge.on('disconnected', function (ctx) {
      console.log('🚀 ~ file: hello.html:78 ~ ctx:', ctx);
      // do whatever you need in case of disconnect from server
    });
    const getToken = async () => {
      const token = await handleSubscriptionToken(statistics, socketData.token);
      return token;
    };
    const subToken = await getToken();
    console.log(
      '🚀 ~ file: hello.html:69 ~ handleSubscribeWebsocket ~ subToken:',
      subToken
    );
    subscription = centrifuge.newSubscription(statistics, {
      token: subToken,
      getToken: getToken
    });
    subscription.on('publication', function (ctx) {
      console.log('🚀 ~ file: HomeCounter.tsx:41 ~ ctx:', ctx);
      // handle new Publication data coming from channel "news".
      console.log(ctx.data);
    });
    subscription.on('unsubscribed', function (ctx) {
      console.log(ctx);
    });
    subscription.on('error', function (ctx) {
      console.log(ctx);
    });
    subscription.subscribe();
    centrifuge.connect();
  };
  // unsubscribe
  function unsubscribe() {
    subscription.unsubscribe();
    subscription.removeAllListeners();
  }
  function presence() {
    subscription.presence().then(
      function (ctx) {
        console.log(ctx.clients);
      },
      function (err) {
        // presence call failed with error
      }
    );
  }

  // Viewing Historical Messages
  function history() {
    subscription.history({ limit: 100 }).then(
      function (message) {
        console.log(message);
      },
      function (err) {
        console.log(err);
      }
    );
  }

  // Close the connection
  function closeit() {
    centrifuge.disconnect();
  }
</script>

文章来源:https://blog.csdn.net/sinat_36728518/article/details/135227927
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。