47 lines
1.3 KiB
Markdown
47 lines
1.3 KiB
Markdown
# Smart WebSocket
|
|
|
|
```js
|
|
// constructor(socketAddress, options = [], autoReconnect = true, debugName = null)
|
|
// debugName is used for console logs. If omitted socketAddress will be used instead.
|
|
let socket = SmartWebSocket("ws://127.0.0.1:8080", [], true, "sock");
|
|
|
|
socket.url = "ws://127.0.0.1:8081";
|
|
socket.protocols = [];
|
|
socket.debugName = "mySock";
|
|
|
|
// close if connection is open, then re-open connection
|
|
// applies changes to socket.url and socket.protocols
|
|
socket.reconnect()
|
|
|
|
// internal WebSocket element.
|
|
console.log(socket.socket);
|
|
|
|
// 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);
|
|
});
|
|
|
|
// close socket and disable auto-reconnect
|
|
socket.close()
|
|
``` |