NodeJS Server API
The Krmx server implementation is a NodeJS backend server and is written in TypeScript.
Take a look at the TypeScript SDK reference and source code (opens in a new tab) to learn more about the Server API.
If you need help setting up a project with Krmx, then please following the instructions at Getting Started.
Creating a Server
A Krmx server can be created using the createServer
method.
import { createServer, Props } from '@krmx/server';
const props: Props = { /* configure here */ }
const server = createServer(props);
Props
When creating a server, configuration properties can be passed to configure it. The exported Props interface describes these properties.
The Krmx server doesn't start listening for incoming connections until
server.listen(<port-number>)
is invoked.
Lifetime
During the server lifetime, the server status can be used to identify the current state us of the server.
import { Server, Status } from '@krmx/server';
declare const server: Server;
const status: Status = server.getStatus();
The different status are described by the Status type. The server can change status by using the listen
and close
methods on the server.
import { Server } from '@krmx/server';
declare const server: Server;
// start listening
const PORT = 8082
server.listen(PORT);
// close the server
server.close();
User Management
You can join, kick, or unlink specific users.
import { Server, User } from '@krmx/server';
declare const server: Server;
// get all users
const users: User[] = server.getUsers();
console.info(users); // [{ username: 'simon', isLinked: true }, ... ]
// join, kick, or unlink a specific user
const username = 'simon';
server.join(username);
server.kick(username);
server.unlink(username);
See the Server interface for more information about these methods.
User Authentication
Right before a connection links to a user, the server emits an authenticate event with some information about the connection. Within this listener you have the ability to reject that connection from linking to the user.
Synchronous
The authenticate
event listener can be used in a synchronous context. This is useful when you need to perform a synchronous operation, such as validating the amount of users already on the server.
import { Server } from '@krmx/server';
declare const server: Server;
server.on('authenticate', (username, info, reject) => {
// example: don't let a new user join if the server is full.
if (info.isNewUser && server.getUsers().length >= 10) {
reject('server is full');
}
});
See the server Events type for more information about the authenticate event.
Asynchronous
The authenticate
event listener can be used in an async context. This is useful when you need to perform an asynchronous operation, such as a database query, to validate the authentication.
import { Server } from '@krmx/server';
declare const server: Server;
server.on('authenticate', (username, info, reject, markAsync) => markAsync(async () => {
// example: authenticate a user using a database query
if (info.auth === undefined || !await myAsyncDatabaseQuery(username, info.auth)) {
reject('authentication failed');
}
}));
Note: The fourth argument in the authenticate event listener is the
markAsync
function. This function is a helper function that wraps the async handler. This allows you to useawait
to perform asynchronous operations.
See the server Events type for more information about the authenticate event.
Send/Broadcast Messages
Once a server is running, you can broadcast or send messages.
import { Server } from '@krmx/server';
declare const server: Server;
// broadcast a message to all linked users
const message = { type: 'my/custom', payload: 3 };
server.broadcast(message);
// send a message to a specific user
const username = 'simon';
server.send(username, message);
See the Server interface for more information about these methods.
Events
You can listen to events, such as joining of new users, using an event listener. To do this you can use the server's on(eventName, listener): void;
method.
Krmx Events
Krmx emits events whenever: a user joins, a connection links to a user, a connection unlinks from a user, a user leaves, and more.
import { Server } from '@krmx/server';
declare const server: Server;
// example of listening to the 'link' event with an event listener
server.on('link', (username) => {
console.info('A connection was linked to ', username);
});
You can find the explanation of each event type in the event-based documentation and in the TypeScript SDK reference.
Messages (from clients)
When clients send messages, these will be emitted as a message
event. You can listen to these message using the server's on('message', <listener>)
method.
import { Server } from '@krmx/server';
declare const server: Server;
server.on('message', (username, message) => {
console.info(username, 'sent:', message);
});
Advanced Usage
You can use the event system to implement more advanced features.
Example: Inactivity Timeouts
In the below example, a user is kicked from the server if they have been offline (unlinked from a connection) for more than one minute.
import { Server } from '@krmx/server';
declare const server: Server;
const inactivitySeconds = 60;
const inactivityTimeouts: Map<string, ReturnType<typeof setTimeout>> = new Map();
const stopInactivityCountDown = (username: string) => {
if (inactivityTimeouts.has(username)) {
clearTimeout(inactivityTimeouts.get(username)!);
inactivityTimeouts.delete(username);
}
}
const startInactivityCountDown = (username: string) => {
inactivityTimeouts.set(username, setTimeout(() => {
console.info(`kicking ${username} due to being offline for too long`);
server.kick(username);
}, inactivitySeconds * 1000));
}
server.on('join', startInactivityCountDown);
server.on('link', stopInactivityCountDown);
server.on('unlink', startInactivityCountDown);
server.on('leave', stopInactivityCountDown);
Example: More coming soon...
More coming soon!
- Pipe
pipe<NextEventMap>(configureTap): EventEmitter<NextEventMap>;
- Events TypeScript Type
TypeScript SDK Reference
Take a look at the TypeScript SDK reference and source code (opens in a new tab) to learn more about the Server API.