@machinat/websocket
TypeScript icon, indicating that this package has built-in type declarations

0.6.0 • Public • Published

WebSocket Module

This package is an underlying module of webview platform for serving WebSocket. You might want to use @machinat/webview unless you want to serve your own web service.

Install

npm install @machinat/core @machinat/http @machinat/websocket
# or with yarn
yarn add @machinat/core @machinat/http @machinat/websocket

Docs

Check the package reference.

Setup

Back-end

import Machinat from '@machinat/core';
import Http from '@machinat/http';
import WebSocket from '@machinat/websocket';

const DEV = process.env.NODE_ENV !== 'production';

const app = Machinat.createApp({
  modules: [
    Http.initModule({ /* ... */ }),
  ],
  platforms: [
    WebSocket.initModule({ entryPath: '/websocket' }),
  ],
  service: [
    { // same origin policy
      provide: WebSocket.UpgradeVerifier,
      withValue: ({ headers }) => headers.origin === 'https://your.domain.com',
    },
  ]
}).onEvent(async ({ bot, event }) => {
  // send a event when a connection is open
  if (event.type === 'connect') {
    await bot.send({
      category: 'greeting',
      type: 'hello',
      payload: 'world',
    });
  }
});

Front-end

import Client from '@machinat/websocket/client';

const client = new Client({ url: '/websocket' });

client.onEvent(async ({ event }) => {
  if (event.type === 'hello') {
    await client.send({
      category: 'greeting',
      type: 'hello',
      payload: 'websocket',
    });
  }
});

Dependents (1)

Package Sidebar

Install

npm i @machinat/websocket

Weekly Downloads

0

Version

0.6.0

License

MIT

Unpacked Size

156 kB

Total Files

79

Last publish

Collaborators

  • lrills0515
  • lrills