Giter Site home page Giter Site logo

mat-sz / typesocket Goto Github PK

View Code? Open in Web Editor NEW
25.0 4.0 1.0 181 KB

๐ŸŒ TypeScript WebSockets library.

Home Page: https://www.npmjs.com/package/typesocket

License: BSD 3-Clause Clear License

TypeScript 100.00%
typescript typescript-library websockets websocket-library websocket javascript

typesocket's Introduction

TypeSocket

TypeScript WebSocket wrapper with disconnection handling and JSON parsing.

workflow npm npm NPM

Are you a React.js user? You might be interested in the useTypeSocket React hook.

Used in filedrop-web and whiteboard-web.

API is mostly stable. It may change in the future, but the changes shouldn't be breaking.

Installation

TypeSocket is available on npm, you can install it with either npm or yarn:

npm install typesocket
# or:
yarn install typesocket

Example usage

const socket = new TypeSocket<MessageModel>(url, {
  maxRetries: 10,
});

socket.on('connected', () => {
  console.log('connected!');

  socket.send({
    type: 'ping',
  });
});

socket.on('message', (message: MessageModel) => {
  console.log(message.type);
});

socket.on('disconnected', () => {
  console.log('disconnected');
});

socket.connect();

With Redux:

I use TypeSocket with Redux and Redux-Saga like this:

export const socketMiddleware = (url: string) => {
  return (store: MiddlewareAPI<any, any>) => {
    const socket = new TypeSocket<MessageModel>(url);

    socket.on('connected', () =>
      store.dispatch({ type: ActionType.WS_CONNECTED }),
    );
    socket.on('disconnected', () =>
      store.dispatch({ type: ActionType.WS_DISCONNECTED }),
    );
    socket.on('message', message =>
      store.dispatch({ type: ActionType.WS_MESSAGE, value: message }),
    );
    socket.connect();

    return (next: (action: any) => void) => (action: any) => {
      if (
        action.type &&
        action.type === ActionType.WS_SEND_MESSAGE &&
        socket.readyState === 1
      ) {
        socket.send(action.value);
      }

      return next(action);
    };
  };
};

Events

You can attach event listeners to an instance of TypeSocket with .on:

socket.on('message', message => {
  console.log(message);
});

connected

Emitted when a connection gets established.

disconnected

Emitted when the socket is disconnected.

permanentlyDisconnected

Emitted when the socket is permanently disconnected, for example:

  • Server gracefully closes the connection.
  • Client gracefully closes the connection.
  • disconnect is called.
  • Retry amount has been exceeded.

message

Emitted when a valid message is received.

The only argument contains an object of type T with a deserialized message.

invalidMessage

Emitted when an invalid message is received.

The only argument contains an object of type string | ArrayBuffer with a raw message.

rawMessage

Emitted when any message is received.

The only argument contains an object of type string | ArrayBuffer with a raw message.

binaryMessage

Emitted when a binary message (with an ArrayBuffer) is received.

The only argument contains an object of type ArrayBuffer.

API

on(eventType: 'message', listener: (message: T) => void);
on(eventType: 'rawMessage' | 'invalidMessage', listener: (message: string | ArrayBuffer) => void);
on(eventType: 'binaryMessage', listener: (message: ArrayBuffer) => void);
on(eventType: 'connected' | 'disconnected' | 'permanentlyDisconnected', listener: () => void);

off(eventType: 'message', listener: (message: T) => void);
off(eventType: 'rawMessage' | 'invalidMessage', listener: (message: string | ArrayBuffer) => void);
on(eventType: 'binaryMessage', listener: (message: ArrayBuffer) => void);
off(eventType: 'connected' | 'disconnected' | 'permanentlyDisconnected', listener: () => void);

constructor(private url: string, options?: TypeSocketOptions);
connect();
disconnect();
send(data: T);
sendRaw(data: string | ArrayBuffer | Blob | ArrayBufferView);
get readyState();

typesocket's People

Contributors

mat-sz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.