A "smart" wrapper for Javascript WebSockets
This repository has been archived on 2025-03-06. You can view files and clone it, but cannot push or open issues or pull requests.
Go to file
Luca Conte fc082c45e8 add SmartWebSocket.js and documentation 2024-08-21 16:57:49 +02:00
README.md add SmartWebSocket.js and documentation 2024-08-21 16:57:49 +02:00
SmartWebSocket.js add SmartWebSocket.js and documentation 2024-08-21 16:57:49 +02:00

README.md

Smart WebSocket

// constructor(socketAddress, options = [], autoReconnect = true, debugName = null)
let socket = SmartWebSocket("ws://127.0.0.1:8080", [], true, "sock"); 

// close if connection is open, then re-open connection
socket.reconnect()

// close socket and disable auto-reconnect
socket.close()

// is socket connection open
if (socket.isReady()) {

	// sends
	// {"event" : "myEvent", "data" : { "abc" : "def" }}
	// to server
	// data is stringified using JSON before sending
	socket.send("myEvent", { "abc" : "def"});

	// sends
	// abcdef
	// to server. Same as calling socket.send on a regular WebSocket
	socket.sendRaw("abcdef");
}

// is called when a JSON of the kind {"event" : "anotherEvent", "data" : {}} is received
socket.on("anotherEvent", (data) => {
	console.log(data);
});

// same as calling socket.addEventListener("open") on a regular WebSocket
// same behaviour applies to events "close", "error" and "message"
socket.on("open", (event) => {
	console.log(event);
});