This code is intended to be a basic abstraction of the base websocket API which you can then build your websocket around.
This code is written with the intent that it be taken and changed as needed to fit the needs of your individual projects. Hence why it does not have an npm
repository set up.
Creating a new WebSocket server instance is as easy as calling new WebsocketProvider(port)
you can then set parameters and event listeners.
const init = async (): void => {
const socket: WebsocketProvider = new WebsocketProvider(8080);
socket.on("message",(message: string) => {
console.log(message);
});
if(!(await socket.connect())) return console.error('Unable to start the connection!');
socket.send('hello world');
}
init();
There are four events that you can listen for; connect
, message
, close
, and error
.
NOTE: Event listeners must be defined before you start the WebSocket connection
socket.on('connect',(connection: WebSocket) => {
});
socket.on('message',(message: string) => {
});
socket.on('close',() => {
});
socket.on('error',() => {
});
Listen for an event to fire.
Open the WebSocket connection.
Send a message over the connection.
- param
message
- The message to be sent. - throws - An error if you try to send a message when the connection is closed.
Ping the connection.
- throws - An error if you try to ping the connection while it's closed.
Close the connection.
Creating a subscriber is as easy as making a provider.
const init = async (): void => {
const uri = new URIBuilder()
.setProtocol(StandardProtocol.WS)
.setHostname("localhost")
.setPort(8080)
.build();
const socket = new WebsocketSubscriber(uri);
socket.reconnect(2);
socket.on("message",(message: string) => {
console.log(message);
});
if(!(await socket.connect())) throw new Error('Unable to start the connection!');
}
init();
There are five events that you can listen for; connect
, message
, close
, error
, and close
.
NOTE: Event listeners must be defined before you start the WebSocket connection
socket.on('connect',(connection: WebSocket) => {
});
socket.on('message',(message: string) => {
});
socket.on('close',() => {
});
socket.on('error',() => {
});
socket.on('reconnect',() => {
});
Listen for an event to fire.
Open the WebSocket connection.
Send a message over the connection.
- param
message
- The message to be sent. - throws - An error if you try to send a message when the connection is closed.
Ping the connection.
- throws - An error if you try to ping the connection while it's closed.
Close the connection.
Kill the connection. The only difference between this and .close()
is that this will not allow the connection to be restarted; even if .reconnect()
has been set.
Set this Websocket to attempt to reconnect after a delay (in seconds). Default's to disabled
- param
delay
- Defaultnull
- The amount of time to wait (in seconds) before attempting to reconnect. If set tonull
, the connection will not attempt to reconnect on close.