3.4.84 • Published 4 months ago

angelia.io v3.4.84

Weekly downloads
343
License
GPL
Repository
github
Last release
4 months ago

angelia.io

WebSockets Server and Client API for node.js and the browser, (with rooms support in development).

The goal of this project is to provide a developer friendly API that just works™.

Installation

Install on node.js/browser npm install angelia.io

If you fancy for Client side a regular JavaScript file, then use https://github.com/titoBouzout/angelia.io/blob/master/client/index.js and include it as a regular script tag.

Simple Example

// server.js (node.js)
import Server from 'angelia.io/server';

class FancyChat {
	async typing(socket, data, callback) {
		console.log('Im', data ? ' typing' : ' not typing')
	}
	async theMessage(socket, data, callback) {
		console.log('the message is', data, socket)
		socket.emit('gotIt', 'thanks')
		callback('yes Im sure')
	}
}

Server.on(FancyChat);

class Connection {
	async connect(socket, request) {
		console.log('socket connected', socket)
	}
	async disconnect(socket, code, message) {
		console.log('socket disconnected', code, message, socket);
	}
}
Server.on(Connection);

Server.listen({
	port: 3001,
});

// index.js (browser)
import Client from 'angelia.io/client';

const socket = new Client('ws://localhost:3001');

socket.emit('typing', true)

setTimeout(() => {
	socket.emit('typing', false)
	socket.emit('theMessage', 'hi there!', (data) =>{
		console.log('you sure?', data)
	})
}, 10000)

socket.on('gotIt', (message) => {
	console.log('Server got it yey', message)
})

Server Documentation (Node.js)

A call to Server.listen starts the server. Server is a singleton and can only have running 1 server.

// server.js (node.js)
import Server from 'angelia.io/server'

Server.listen({
	hostname: 'localhost',
	port: 3001,
	maxMessageSize: 5,
	cert: '/path/to/cert/fullchain.pem',
	key: '/path/to/key/privkey.pem',
})

Server Options

namekinddefaultdescription
hostnameString''the hostname if any
portNumber3001the port to use for this server
maxMessageSizeNumber5max size in mb of a message received
skipUTF8ValidationBooleanfalseallows to skip utf8 validation
certString''path to the cert file for using https fullchain.pem
keyString''path to the key file for using https privkey.pem
httpnode servernullin case you want to use your own server. Else one will be created, as in require('http(s)').createServer()
timeoutNumber60000time in milliseconds after a socket is considered gone, minimun value is 10000

Server Object

The server object can be accessed from everywhere

// server.js (node.js)
import Server from 'angelia.io/server'

class _ {
	connect(socket, request) {
		console.log(this.server, 'also', socket.server)
	}
}
Server.on(_)

Server.listen({
	port: 3001,
})

List of Server Object Properties

signaturekinddescription
sinceNumbertimestamp of initialization
nowNumbertimestamp that updates every half a second
portNumberport used by this server
hostnameStringthe hostname if any
maxMessageSizeNumbermaximum message size in mb
timeoutNumberafter how long the socket is considered gone, in ms
connectionsNumbercount of sockets connected
servedNumbercount of sockets ever connected
bytesSentNumbersum of bytes sent by the server
bytesReceivedNumbersum of bytes the server has ever received
messagesSentNumbercount of messages ever sent
messagesReceivedNumbercount of messages ever received
eventsObjectref to events, ex: server.events.typing() to dispatch typing to anyone listening to it
listenersArrayfor debbuging: array of listeners as strings
on(Class)Functionattaches all methods of a Class as listeners
on(Function)Functionattaches a named Function as a listener
on(Object)Functionattaches all properties of an object that are of the type Function as listeners
on(key, Function)Functionattaches a Function as a listener for key
emit(key, [value])Functionemits to all connected sockets
once(key, [value])Functionemits to the sockets and replace if exists a pending message with the same key
broadcast(sender, key, [value])Functionemits to all connected sockets except sender
broadcastOnce(sender, key, [value])Functionemits to the sockets except sender and replace if exists a pending message with the same key
socketsSeta Set() with all the current connected sockets
httpnode serverthe underlying http(s) server

Socket Object

The socket object is given to you by a listener

// server.js (node.js)
import Server from 'angelia.io/server'

class _ {
	connect(socket, request) {
		console.log(socket, request)
	}
}
Server.on(_)

Server.listen({
	port: 3001,
})

List of Socket Object Properties

signaturekinddescription
serverObjectreference to the server
ipStringip of the socket
userAgentStringuser agent of the socket
paramsObjectthe params sent via the client constructor
sinceNumbertimestamp of first seen
seenNumbertimestamp of last received message
pingNumberdelay with the socket in milliseconds (full round trip)
timedoutBooleanwhether we lost connection with this socket
bytesSentNumbersum of bytes sent to this socket
bytesReceivedNumbersum of bytes received from this socket
messagesSentNumbercount of messages sent to this socket
messagesReceivedNumbercount of messages received from this socket
roomsSeta set with the rooms where this socket is in
emit(key, [value])Functionemits to client
once(key, [value])Functionreplace if exists a pending message with the same key from emit queue
disconnect([noReconnect])Functiondisconnects the socket from the server, pass true to prevent re-connections

Listeners

To listen for a client message/event you may do the familiar way Server.on('connect', (socket) => {console.log('socket connected!', socket)})

However, to ease organization and development you may listen to an event by creating a class with any name, and give to methods the name of the things you want to listen to. You then add your class to the listeners as Server.on(MyClass); and you are done.

On user defined listeners, the listener receives three things as sent by the client: socket, data and a callback; Example class FancyChat { async typing(socket, data, callback) {console.log(socket, data);}}.

Syntax For Listeners

Listeners have the following alternative syntax if you feel like

// server.js (node.js)
import Server from 'angelia.io/server'

// listen via the names of methods of a class
Server.on(
	class Connection {
		async connect(socket, request) {
			console.log('connect in Class')
		}
		async something(socket, data, callback) {
			console.log('something is dispatched')
		}
	},
)

// listen via the name of a function
Server.on(function connect(socket, request) {
	console.log('connect in Function')
})

// listen via the properties of an object to all the functions of it
Server.on({
	connect: function (socket, request) {
		console.log('connect in Object')
		this.works()
	},
	works: function () {
		console.log('this works yep')
	},
})

// named listener with callback
Server.on('connect', (socket, request) => {
	console.log('connect in arrow function')
})

// named listener with a random named callback (the callback name doesn't matter)
Server.on('connect', function fancyConnect(socket, request) {
	onsole.log('connect in named function')
})

Server.listen({
	port: 3001,
})

Predefined Server Events

There's a bunch of handy predefined events dispatched whenever you add listeners for them.

// server.js (node.js)
import Server from 'angelia.io/server';

class _ {
	async listen() {
		console.log('Server started listening on port ' + this.server.port);
	}
	async connect(socket, request) {
		console.log('a socket connected!', socket)
	}
	...
}

Server.on(_);

Server.listen({
	port: 3001,
});

List of Predefined Server Events

signaturedescription
listen()when the server is about to listen
connect(socket, request)when a socket connects
disconnect(socket, code, message)when a socket gets disconnected
ping(socket)when we got an update of the ping for a socket
timeout(socket, delay)when we are about to disconnect the socket, gives the delay in milliseconds
garbage(socket, data)if the client sends a message that the server has no listener this will be dispatched
incoming(socket, messages)for debugging: ref to array of incoming messages received before dispatching to listeners
outgoing(socket, messages)for debugging: ref to array of outgoing messages before sending to socket

this object on listeners has some predefined properties

propertydescription
serverreference to server object
eventsreference to event dispatcher, ex: this.events.typing() will dispatch the typing event to anyone listening to it
classesreference to all functions that have been attached as listeners , ex: this.classes.MyFancyChat.typing

Client API (Browser)

Client Options

Configurable options used by the constructor

const socket = new Client({
	url: 'ws://localhost:3001',
	params: function () {
		return { fast: 'data', test: 'a space' }
	},
})
propertykinddefaultdescription
urlstring'ws(s)://\${window.location.hostname}:3001'url of the socket server, example 'ws://localhost:3001'
paramsFunction{}to send data while connecting, accesible via socket.params server side
longLiveFlashbooleanfalsebrowsers throw when calling swf functions via ExternalInterface after events like WebSocket.onmesssage; setting this to true fix it by dispatching them in a setTimeout
dontConnectBooleanfalseallows to instance the socket without connecting

You may also do like this if you don't need any option

const socket = new Client('ws://localhost:3001')

Client API

The client API is similar to regular event handling

signaturekinddescription
connectedBooleantrue when the socket is connected else false
connect()Functionconnects to the server, it auto-connects on disconnection
disconnect([noReconnect])Functiondisconnects from the server, pass true to prevent re-connections
on(key, callback)Functionlistens for an event, returns an off function to stop listening
off(key, callback)Functionturns off listening for an event
emit(key, [value, callback])Functionemits data to the server
decode(data)Functionfor decoding binary data, returns a promise

List of Predefined Client Events

As in socket.on('connect', () => console.log('connect happened!'))

signaturedescription
connectthis happens only once when we connect to the server, any future connection is a reconnect
reconnectif we were connected at least once, then any reconnection will dispatch this event instead of connect
disconnectwhen we disconnect from the server

Authors

URLs

3.4.84

4 months ago

3.4.83

5 months ago

3.4.80

5 months ago

3.4.81

5 months ago

3.4.82

5 months ago

2.4.79

6 months ago

2.4.70

2 years ago

2.2.0

2 years ago

2.3.68

2 years ago

2.4.76

2 years ago

2.4.75

2 years ago

2.4.78

2 years ago

2.4.77

2 years ago

2.4.72

2 years ago

2.4.71

2 years ago

2.4.74

2 years ago

1.65.0

2 years ago

2.4.73

2 years ago

1.67.0

2 years ago

1.64.0

2 years ago

2.1.0

2 years ago

1.66.0

2 years ago

2.4.69

2 years ago

1.61.0

2 years ago

1.63.0

2 years ago

1.62.0

2 years ago

1.60.0

3 years ago

1.59.0

3 years ago

1.58.0

3 years ago

1.57.0

3 years ago

1.56.0

3 years ago

1.55.0

3 years ago

1.53.0

3 years ago

1.54.0

3 years ago

1.52.0

3 years ago

1.51.0

3 years ago

1.50.0

3 years ago

1.46.0

3 years ago

1.48.0

3 years ago

1.47.0

3 years ago

1.49.0

3 years ago

1.45.0

3 years ago

1.42.0

3 years ago

1.44.0

3 years ago

1.43.0

3 years ago

1.41.0

3 years ago

1.37.0

3 years ago

1.38.0

3 years ago

1.39.0

3 years ago

1.40.0

3 years ago

1.36.0

3 years ago

1.34.0

3 years ago

1.35.0

3 years ago

1.33.0

3 years ago

1.32.0

3 years ago

1.29.0

3 years ago

1.28.0

3 years ago

1.30.0

3 years ago

1.31.0

3 years ago

1.27.0

3 years ago

1.26.0

3 years ago

1.25.0

3 years ago

1.24.0

3 years ago

1.19.0

3 years ago

1.18.0

3 years ago

1.17.0

3 years ago

1.21.0

3 years ago

1.22.0

3 years ago

1.20.0

3 years ago

1.23.0

3 years ago

1.15.0

3 years ago

1.16.0

3 years ago

1.14.0

3 years ago

1.13.0

3 years ago

1.12.0

3 years ago

1.11.0

3 years ago

1.10.0

3 years ago

1.9.0

3 years ago

1.8.0

3 years ago

1.7.0

3 years ago

1.6.0

3 years ago

1.5.0

3 years ago

1.4.0

3 years ago

1.3.0

3 years ago

1.1.0

3 years ago

1.0.1

3 years ago