@999-cs/websocket-it
v2.0.1
Published
A simple and flexible WebSocket server library that extends `EventEmitter` to handle custom events. This library allows you to easily create and manage WebSocket servers, either by providing a port number or using an existing `WebSocketServer` instance.
Downloads
9
Readme
@999-cs/websocket-it Library
A simple and flexible WebSocket server library that extends EventEmitter
to handle custom events. This library allows you to easily create and manage WebSocket servers, either by providing a port number or using an existing WebSocketServer
instance.
Installation
You can install this library using npm:
npm install @999-cs/websocket-it
Usage
Creating a New WebSocket Server
You can create a new WebSocket server by providing a port number:
const { websocketIt } = require("@999-cs/websocket-it");
const port = 8080;
const server = websocketIt.createServer({ port });
server.on("connection", (ws) => {
console.log("A new client has connected");
});
server.on("messageCreate", (data) => {
console.log("messageCreate event received with data:", data);
//server.wss.clients -> Get all clients
//server.WebSocket -> try it by yourself and discover what this property do
});
server.on("close", () => {
console.log("A client has disconnected");
});
server.on("error", (error) => {
console.error(`An error occurred: ${error}`);
});
console.log(`WebSocket server started on port ${port}`);
Using an Existing WebSocket Server
You can also use an existing WebSocketServer
instance:
const { WebSocketServer } = require("ws");
const { websocketIt } = require("@999-cs/websocket-it");
const existingWss = new WebSocketServer({ port: 8081 });
const server = websocketIt.createServer({ wss: existingWss });
server.on("connection", (ws) => {
console.log("A new client has connected");
});
server.on("messageCreate", (data) => {
console.log("messageCreate event received with data:", data);
});
server.on("close", () => {
console.log("A client has disconnected");
});
server.on("error", (error) => {
console.error(`An error occurred: ${error}`);
});
console.log(`WebSocket server is using an existing instance on port 8081`);
Usage from Frontend
To connect to the WebSocket server from the frontend, you can use the WebSocket
API available in modern browsers. Below is an example of how to connect to the WebSocket server and handle events.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<input type="text" id="messageInput" placeholder="Type a message" />
<button onclick="sendMessage()">Send Message</button>
<div id="output"></div>
<script>
const socket = new WebSocket("ws://localhost:8080");
socket.onopen = () => {
console.log("Connected to the server");
document.getElementById('output').innerHTML += "<p>Connected to the server</p>";
};
socket.onmessage = (event) => {
const message = event.data;
console.log("Received:", message);
document.getElementById('output').innerHTML += `<p>Received: ${message}</p>`;
};
socket.onclose = () => {
console.log("Disconnected from the server");
document.getElementById('output').innerHTML += "<p>Disconnected from the server</p>";
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
document.getElementById('output').innerHTML += `<p>Error: ${error}</p>`;
};
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value;
// It is important to send an object with the correct structure
const eventMessage = JSON.stringify({
eventName: "messageCreate",
data: { text: message }
});
socket.send(eventMessage);
console.log("Sent:", eventMessage);
document.getElementById('output').innerHTML += `<p>Sent: ${eventMessage}</p>`;
input.value = '';
}
</script>
</body>
</html>
Note: It is important to send an object with the correct structure:
{
eventName: "messageCreate",
data: { text: message,author : "someone" }
}
The correct structure includes two properties:
eventName
: A string representing the name of the event.data
: An object containing the data associated with the event.
The correct structure includes these two properties to ensure that the server can correctly process and respond to the events.