All Projects → insidewhy → Rxjs Websockets

insidewhy / Rxjs Websockets

Licence: isc
A very flexible and simple websocket library for rxjs

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Rxjs Websockets

Websocket
WSServer is a fast, configurable, and extendable WebSocket Server for UNIX systems written in C (C11).
Stars: ✭ 144 (-41.94%)
Mutual labels:  websocket, websockets
Stuhome
📱 An iOS client for https://bbs.uestc.edu.cn/ written in react-native, redux and redux-observable.
Stars: ✭ 241 (-2.82%)
Mutual labels:  rxjs, redux-observable
Angular Nodejs Mongodb Customersservice
Code for the Integrating Angular with Node.js RESTful Services Pluralsight course.
Stars: ✭ 164 (-33.87%)
Mutual labels:  rxjs, observables
Tap Tap Adventure
Tap Tap Adventure is a massively online 2D MMORPG set in the medieval times with twists.
Stars: ✭ 123 (-50.4%)
Mutual labels:  websocket, websockets
Async Tungstenite
Async binding for Tungstenite, the Lightweight stream-based WebSocket implementation
Stars: ✭ 207 (-16.53%)
Mutual labels:  websocket, websockets
Bolt Js
A framework to build Slack apps using JavaScript
Stars: ✭ 1,971 (+694.76%)
Mutual labels:  websocket, websockets
Claws
Awesome WebSocket CLient - an interactive command line client for testing websocket servers
Stars: ✭ 187 (-24.6%)
Mutual labels:  websocket, websockets
Webfluxtemplate
Spring Webflux template application with working Spring Security, Web-sockets, Rest, Web MVC, and Authentication with JWT.
Stars: ✭ 107 (-56.85%)
Mutual labels:  websocket, websockets
Bolt Python
A framework to build Slack apps using Python
Stars: ✭ 190 (-23.39%)
Mutual labels:  websocket, websockets
Speechtotext Websockets Javascript
SDK & Sample to do speech recognition using websockets in Javascript
Stars: ✭ 191 (-22.98%)
Mutual labels:  websocket, websockets
Rxios
A RxJS wrapper for axios
Stars: ✭ 119 (-52.02%)
Mutual labels:  rxjs, observables
Django Sockpuppet
Build reactive applications with the django tooling you already know and love.
Stars: ✭ 225 (-9.27%)
Mutual labels:  websocket, websockets
Php Wss
Web-socket server/client with multi-process and parse templates support on server and send/receive options on client
Stars: ✭ 117 (-52.82%)
Mutual labels:  websocket, websockets
Redux Most
Most.js based middleware for Redux. Handle async actions with monadic streams & reactive programming.
Stars: ✭ 137 (-44.76%)
Mutual labels:  rxjs, redux-observable
Types First Ui
An opinionated framework for building long-lived, maintainable UI codebases
Stars: ✭ 114 (-54.03%)
Mutual labels:  rxjs, redux-observable
Ws Tcp Relay
A simple relay between WebSocket clients and TCP servers
Stars: ✭ 186 (-25%)
Mutual labels:  websocket, websockets
Example App
Example app showcasing the ngrx platform
Stars: ✭ 1,361 (+448.79%)
Mutual labels:  rxjs, observables
Linkphp
基于swoole一款高性能多进程常驻内存型全栈框架,内置WebSocket服务器、服务治理PhpRpc功能,不依赖传统的 PHP-FPM,可以用于构建高性能的Web系统、API、中间件、基础服务等等。
Stars: ✭ 101 (-59.27%)
Mutual labels:  websocket, websockets
Javawebsocketclient
RxJava WebSocket library for Java and Android
Stars: ✭ 188 (-24.19%)
Mutual labels:  websocket, websockets
Isomorphic Ws
Isomorphic implementation of WebSocket (https://www.npmjs.com/package/ws)
Stars: ✭ 215 (-13.31%)
Mutual labels:  websocket, websockets

rxjs-websockets

build status Known Vulnerabilities Renovate

An rxjs websocket library with a simple and flexible implementation. Supports the browser and node.js.

Comparisons to other rxjs websocket libraries:

  • observable-socket
    • observable-socket provides an input subject for the user, rxjs-websockets allows the user to supply the input stream as a parameter to allow the user to select an observable with semantics appropriate for their own use case (queueing-subject can be used to achieve the same semantics as observable-socket).
    • With observable-socket the WebSocket object must be used and managed by the user, rxjs-websocket manages the WebSocket(s) for the user lazily according to subscriptions to the messages observable.
    • With observable-socket the WebSocket object must be observed using plain old events to detect the connection status, rxjs-websockets presents the connection status through observables.
  • rxjs built-in websocket subject
    • Implemented as a Subject so lacks the flexibility that rxjs-websockets and observable-socket provide.
    • Does not provide any ability to monitor the web socket connection state.

Installation

npm install -S rxjs-websockets
# or
yarn add rxjs-websockets

Changelog

Changelog here

Simple usage

import { QueueingSubject } from 'queueing-subject'
import { Subscription } from 'rxjs'
import { share, switchMap } from 'rxjs/operators'
import makeWebSocketObservable, {
  GetWebSocketResponses,
  // WebSocketPayload = string | ArrayBuffer | Blob
  WebSocketPayload,
  normalClosureMessage,
} from 'rxjs-websockets'

// this subject queues as necessary to ensure every message is delivered
const input$ = new QueueingSubject<string>()

// queue up a request to be sent when the websocket connects
input$.next('some data')

// create the websocket observable, does *not* open the websocket connection
const socket$ = makeWebSocketObservable('ws://localhost/websocket-path')

const messages$: Observable<WebSocketPayload> = socket$.pipe(
  // the observable produces a value once the websocket has been opened
  switchMap((getResponses: GetWebSocketResponses) => {
    console.log('websocket opened')
    return getResponses(input$)
  }),
  share(),
)

const messagesSubscription: Subscription = messages.subscribe(
  (message: string) => {
    console.log('received message:', message)
    // respond to server
    input$.next('i got your message')
  },
  (error: Error) => {
    const { message } = error
    if (message === normalClosureMessage) {
      console.log('server closed the websocket connection normally')
    } else {
      console.log('socket was disconnected due to error:', message)
    }
  },
  () => {
    // The clean termination only happens in response to the last
    // subscription to the observable being unsubscribed, any
    // other closure is considered an error.
    console.log('the connection was closed in response to the user')
  },
)

function closeWebsocket() {
  // this also caused the websocket connection to be closed
  messagesSubscription.unsubscribe()
}

setTimeout(closeWebsocket, 2000)

The observable returned by makeWebSocketObservable is cold, this means the websocket connection is attempted lazily as subscriptions are made to it. Advanced users of this library will find it important to understand the distinction between hot and cold observables, for most it will be sufficient to use the share operator as shown in the example above. The share operator ensures at most one websocket connection is attempted regardless of the number of subscriptions to the observable while ensuring the socket is closed when the last subscription is unsubscribed. When only one subscription is made the operator has no effect.

By default the websocket supports binary messages so the payload type is string | ArrayBuffer | Blob, when you only need string messages the generic parameter to makeWebSocketObservable can be used:

const socket$ = makeWebSocketObservable<string>('ws://localhost/websocket-path')
const input$ = new QueueingSubject<string>()

const messages$: Observable<string> = socket$.pipe(
  switchMap((getResponses: GetWebSocketResponses<string>) => getResponses(input$)),
  share(),
)

Reconnecting on unexpected connection closures

This can be done with the built-in rxjs operator retryWhen:

import { Subject } from 'rxjs'
import { switchMap, retryWhen } from 'rxjs/operators'
import makeWebSocketObservable from 'rxjs-websockets'

const input$ = new Subject<string>()

const socket$ = makeWebSocketObservable('ws://localhost/websocket-path')

const messages$ = socket$.pipe(
  switchMap((getResponses) => getResponses(input$)),
  retryWhen((errors) => errors.pipe(delay(1000))),
)

Alternate WebSocket implementations

A custom websocket factory function can be supplied that takes a URL and returns an object that is compatible with WebSocket:

import makeWebSocketObservable, { WebSocketOptions } from 'rxjs-websockets'

const options: WebSocketOptions = {
  // this is used to create the websocket compatible object,
  // the default is shown here
  makeWebSocket: (url: string, protocols?: string | string[]) => new WebSocket(url, protocols),

  // optional argument, passed to `makeWebSocket`
  // protocols: '...',
}

const socket$ = makeWebSocketObservable('ws://127.0.0.1:4201/ws', options)

JSON messages and responses

This example shows how to use the map operator to handle JSON encoding of outgoing messages and parsing of responses:

import { Observable } from 'rxjs'
import makeWebSocketObservable, { WebSocketOptions } from 'rxjs-websockets'

function makeJsonWebSocketObservable(
  url: string,
  options?: WebSocketOptions,
): Observable<unknown> {
  const socket$ = makeWebSocketObservable<string>(url, options)
  return socket$.pipe(
    map((getResponses: GetWebSocketReponses<string>) => (input$: Observable<object>) =>
      getResponses(input$.pipe(map((request) => JSON.stringify(request)))).pipe(
        map((response) => JSON.parse(response)),
      ),
    ),
  )
}

The function above can be used identically to makeWebSocketObservable only the requests/responses will be transparently encoded/decoded.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].