@elderapo/typed-socket.io-client
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

@elderapo/typed-socket.io

styled with prettier Greenkeeper badge CircleCI Dev Dependencies

Strongly typed websockets library (internally uses SocketIO).

How to install

yarn add @elderapo/typed-socket.io-server @elderapo/typed-socket.io-client
# or
npm install @elderapo/typed-socket.io-server @elderapo/typed-socket.io-client

Example

import {
  ClientSocket,
  ClientSocketStateEvent,
  ClientSocketStateEvents
} from "@elderapo/typed-socket.io-client";
import {
  Server,
  ServerSocketStateEvent,
  ServerSocketStateEvents
} from "@elderapo/typed-socket.io-server";

export enum ClientToServerEvent {
  HelloServer
}

export interface ClientToServerEvents extends ServerSocketStateEvents {
  [ClientToServerEvent.HelloServer]: string;
}

export enum ServerToClientEvent {
  HelloClient
}

export interface ServerToClientEvents extends ClientSocketStateEvents {
  [ServerToClientEvent.HelloClient]: number;
}

const typedIOServer = new Server<ClientToServerEvents, ServerToClientEvents>(
  8000
);

typedIOServer.onConnection(socket => {
  console.log("New connection:", socket.id);

  socket.emit(ServerToClientEvent.HelloClient, 123);

  socket.on(ClientToServerEvent.HelloServer, payload => {
    console.log("Received hello server:", payload);
  });

  typedIOServer.emitToEveryone(ServerToClientEvent.HelloClient, 666);

  socket.on(ServerSocketStateEvent.Disconnect, reason => {
    console.log("ServerSocketStateEvent.Disconnect", reason);
  });
});

const typedIOClient = ClientSocket.connect<
  ClientToServerEvents,
  ServerToClientEvents
>("http://localhost:8000");

typedIOClient.on(ServerToClientEvent.HelloClient, payload => {
  console.log("ServerToClientEvent.HelloClient", payload);
});

typedIOClient.emit(ClientToServerEvent.HelloServer, "HELLOOOO!!");

typedIOClient.on(ClientSocketStateEvent.Connect, () => {
  console.log("ClientStateEvent.Connect");
});

typedIOClient.on(ClientSocketStateEvent.Disconnect, () => {
  console.log("ClientStateEvent.Disconnect");
});

setTimeout(() => {
  typedIOClient.disconnect();
}, 500);

Readme

Keywords

none

Package Sidebar

Install

npm i @elderapo/typed-socket.io-client

Weekly Downloads

5

Version

1.0.5

License

MIT

Unpacked Size

9.24 kB

Total Files

7

Last publish

Collaborators

  • elderapo