Onu2's event system with network capabilities for clients and servers.
This is a wrapper around standard WebSocket connections, which allows you to send and receive type-safe events between clients and servers. EventNetworking can handle reconnects if a WebSocket connection is lost.
npm install https://github.com/OnuGame/eventnetworking
For an example, check out the EventNetworking Example Project.
The shared events are the most important part of EventNetworking. They define your event structure and ensure type safety between clients and servers.
Note: You should define them in a separate package, which can be used by both the client and the server.
Here is an example of a custom event:
import { BaseEvent } from "@lebogo/eventsystem";
export class MyCustomEvent extends BaseEvent {
constructor(public text: string) {
super("MyCustomEvent");
}
}As previously mentioned, EventNetworking is a wrapper around standard WebSocket connections. The Server is based on the ws package.
import { Server as WSServer } from "ws";
import { Server, ClientConnectedEvent, ClientDisconnectedEvent } from "@onu2/event-networking";
import { MyCustomEvent } from "shared"; // Import the shared event from the shared package
const wsServer = new WSServer({
port: 8080,
});
const server = new Server(wsServer);
server.registerEvent<ClientConnectedEvent>("ClientConnectedEvent", (event) => {
const connection = event.connection!;
connection.registerEvent<MyCustomEvent>("MyCustomEvent", (event) => {
console.log(`Received custom event from client ${connection.id}: ${event.text}`);
});
connection.registerEvent<ClientDisconnectedEvent>("ClientDisconnectedEvent", () => {
console.log(`Client ${connection.id} disconnected.`);
});
// Send a custom event to the client
connection.send(new MyCustomEvent("Hello from the server!"));
});The Client behaves slightly different than the Server. It directly implements the Browser's WebSocket API and is not based on any package.
import { Client, ClientDisconnectedEvent } from "@onu2/event-networking";
import { MyCustomEvent } from "shared"; // Import the shared event from the shared package
const client = new Client("ws://localhost:8080");
client.registerEvent<MyCustomEvent>("MyCustomEvent", (event) => {
console.log(`Received custom event with text: ${event.text}`);
client.send(new MyCustomEvent("Hello server, this is client!"));
});
client.registerEvent<ClientDisconnectedEvent>("ClientDisconnectedEvent", () => {
console.log("Disconnected from server.");
});