WebSockets
@marblejs/websockets module implements the RFC 6455 WebSocket protocol, providing full-duplex communication channels over a single TCP connection.
Installation
Bootstrapping
Like httpListener __the WebSocket module defines a similar way of bootstrapping the app.
To create WebSocket app instance, we can use createWebSocketServer
, which is a wrapper around ws
server creator. When created, it won't automatically start listening to given port and hostname until you call its awaited instance.
If you are curious about other ways of server bootstrapping, reach out the HTTP Server events chapter.
Effects
Marble.js defines a common interface for many different kinds Effects. In case of @marblejs/websockets, the module defines a WsEffect
which works within WebSocket protocol and deals with streams of Events. The very basic implementation of WebSocket Effect can look like in the code snipped below.
Like any other Effect, it is just a function which returns a stream of outgoing events. The Effect above responds to HELLO events with Hello, world!
message. In case of default WsEffect
interface, each incoming event has to be mapped to an outgoing event which is just an object with type and payload attributes.
Lets do some cool math! In the next example we will try to build a very basic calculator using only streams! For the example purpose we will only need two Effects: the first that will match ADD events and the second that will match SUM events.
In the example above we did a little bit of RxJS magic using buffer
operator, which buffers the source Observable values until closing notifier emits (in this case sum$
). Additionally, to be sure that incoming ADD events are sent with payload of type number, we used @marblejs/middleware-io validator, which is able to infer payload type from defined schema.
Lets examine in steps how the server will respond to given equation:
Last updated