centrifuge5.0.1版本请求websocket实例

目录

一、安转

二、快速开始 

三、实例开始


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>

相关推荐

  1. centrifuge5.0.1版本请求websocket实例

    2023-12-30 01:58:04       62 阅读
  2. 在next13当中使用centrifuge5.0.1进行websocket请求

    2023-12-30 01:58:04       50 阅读
  3. uniapp如何发送websocket请求

    2023-12-30 01:58:04       23 阅读
  4. WebSocket实战

    2023-12-30 01:58:04       46 阅读
  5. 如何让 Websocket兼容低版本浏览器

    2023-12-30 01:58:04       50 阅读
  6. springboot请求406、500问题

    2023-12-30 01:58:04       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-30 01:58:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-30 01:58:04       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-30 01:58:04       82 阅读
  4. Python语言-面向对象

    2023-12-30 01:58:04       91 阅读

热门阅读

  1. leetcode每日一题41

    2023-12-30 01:58:04       48 阅读
  2. Docker:登录私有仓库\退出私有仓库

    2023-12-30 01:58:04       55 阅读
  3. 【Qt-QString】

    2023-12-30 01:58:04       61 阅读
  4. Seatunnel Docker image镜像制作

    2023-12-30 01:58:04       47 阅读
  5. MyBatis之缓存

    2023-12-30 01:58:04       42 阅读
  6. Nginx和OpenResty面试题及简单示例

    2023-12-30 01:58:04       50 阅读
  7. c语言结构体内存对齐

    2023-12-30 01:58:04       61 阅读
  8. 互联网摸鱼日报(2023-12-26)

    2023-12-30 01:58:04       54 阅读