### config(params) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Allows updating any configuration parameter on the fly after the instance has been created, without needing to recreate the object. This is useful before calling `open()`, for example, when the IP address is provided by the user through a form. ```APIDOC ## config(params) ### Description Allows updating any configuration parameter on the fly after the instance has been created, without needing to recreate the object. This is useful before calling `open()`, for example, when the IP address is provided by the user through a form. ### Method `config` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (object) - Configuration object with parameters to update. - **ip** (string) - Server address. - **port** (number) - Port number. - **proto** (string) - WebSocket subprotocol. - **secure** (boolean) - Use wss://. - **reconnect** (number) - Reconnection interval in ms. ### Request Example ```javascript const ws = new WebSocketJS({ port: 81 }); // Update IP before opening connection document.getElementById('open_b').onclick = () => { ws.config({ ip: document.getElementById('ip_i').value }); ws.open(); }; // Update multiple parameters at once ws.config({ ip: '10.0.0.5', port: 8080, reconnect: 3000 }); ``` ### Response None ``` -------------------------------- ### Handle Successful Connection Opening with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `onopen` callback is executed once the WebSocket connection is successfully established. This example logs a success message and sends an initial text message to the server. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onopen = () => { console.log('Соединение установлено!'); ws.sendText('init'); // сразу отправляем инициализирующее сообщение }; ws.open(); ``` -------------------------------- ### Handle Connection State Changes with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `onchange` callback is called every time the connection state changes. It receives a string representing the new state (e.g., "closed", "opening", "open", "closing"). This example logs the state and updates a status element in the DOM. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onchange = (state) => { console.log('Состояние изменилось:', state); // => "opening" → "open" → "closing" → "closed" const statusEl = document.getElementById('status'); switch (state) { case WebSocketJS.State.Open: statusEl.textContent = 'Подключено'; break; case WebSocketJS.State.Closed: statusEl.textContent = 'Отключено'; break; case WebSocketJS.State.Opening: statusEl.textContent = 'Подключение...'; break; case WebSocketJS.State.Closing: statusEl.textContent = 'Отключение...'; break; } }; ws.open(); ``` -------------------------------- ### Update WebSocketJS Configuration Source: https://context7.com/gyverlibs/websocket.js/llms.txt Modify configuration parameters of an existing WebSocketJS instance on the fly using the `config` method. This is useful before opening a connection, for example, when updating the IP address from user input. ```javascript const ws = new WebSocketJS({ port: 81 }); // Обновляем IP перед открытием соединения document.getElementById('open_b').onclick = () => { ws.config({ ip: document.getElementById('ip_i').value }); ws.open(); }; // Можно обновить несколько параметров сразу ws.config({ ip: '10.0.0.5', port: 8080, reconnect: 3000 }); ``` -------------------------------- ### Handle Binary Messages with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `onbin` callback is triggered upon receiving binary data. The data type is `ArrayBuffer` (set via `binaryType = "arraybuffer"` within the library). This example logs the received bytes after converting the buffer to a Uint8Array. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, proto: 'esp' }); ws.onbin = (buffer) => { const bytes = new Uint8Array(buffer); console.log('Получены байты:', bytes); // => Получены байты: Uint8Array [12, 34, 56] }; ws.open(); ``` -------------------------------- ### Handle Text Messages with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `ontext` callback is invoked when a text message is received from the server. By default, it's an empty function. This example logs the received text and updates the DOM. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.ontext = (text) => { console.log('Получен текст:', text); // => Получен текст: Hello from server document.getElementById('output').textContent = text; }; ws.open(); ``` -------------------------------- ### Handle Connection Closure with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `onclose` callback is invoked when the connection is closed, including cases of lost connection before reconnection attempts. This example logs a message and updates the status display. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, reconnect: 1000 }); ws.onclose = () => { console.log('Соединение закрыто, ожидаем переподключения...'); document.getElementById('status').textContent = 'Отключено'; }; ws.open(); ``` -------------------------------- ### Handle Connection Errors with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `onerror` callback is invoked when a WebSocket error occurs. It receives an error string, typically '[WS] Error'. This example logs the error to the console. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onerror = (err) => { console.error('Ошибка WebSocket:', err); // => Ошибка WebSocket: [WS] Error }; ws.open(); ``` -------------------------------- ### WebSocket.js Connection States Enumeration Source: https://context7.com/gyverlibs/websocket.js/llms.txt The `WebSocketJS.State` is a static object containing constants for connection states. It is used in conjunction with the `onchange` callback to determine the current status of the WebSocket connection. This example demonstrates logging the states and using them to check if the connection is open. ```javascript console.log(WebSocketJS.State); // => { // Closed: 'closed', // Opening: 'opening', // Open: 'open', // Closing: 'closing', // } const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onchange = (s) => { if (s === WebSocketJS.State.Open) { console.log('Готово к отправке данных'); } }; ws.open(); ``` -------------------------------- ### Constructor and Configuration Source: https://github.com/gyverlibs/websocket.js/blob/main/README.md Initialize the WebSocket client and configure its connection parameters. ```APIDOC ## Constructor ### Description Initializes a new instance of the WebSocket client. ### Method `constructor(params = {})` ### Parameters - **params** (object) - Optional - An object containing configuration parameters. - **ip** (string) - The IP address of the WebSocket server. - **port** (number) - The port of the WebSocket server. - **proto** (string) - The protocol to use (e.g., 'ws', 'wss'). - **secure** (boolean) - Whether to use a secure connection (WSS). - **reconnect** (number) - The interval in milliseconds for automatic reconnection. ## Configuration ### Description Configures the WebSocket client with specified parameters. ### Method `config(params = {})` ### Parameters - **params** (object) - Optional - An object containing configuration parameters (same as constructor parameters). ``` -------------------------------- ### Create WebSocketJS Instance Source: https://context7.com/gyverlibs/websocket.js/llms.txt Instantiate WebSocketJS with default or custom configuration parameters. The connection is not opened automatically upon instantiation. ```javascript import WebSocketJS from 'https://gyverlibs.github.io/Websocket.js/Websocket.min.js'; // или: import WebSocketJS from '@alexgyver/websocket'; // Минимальный вариант — все параметры по умолчанию (localhost:81) const ws = new WebSocketJS(); // Полная конфигурация const ws = new WebSocketJS({ ip: '192.168.1.100', // адрес сервера (по умолчанию: "localhost") port: 81, // порт (по умолчанию: 81) proto: 'esp', // субпротокол WebSocket (по умолчанию: undefined) secure: false, // использовать wss:// (по умолчанию: false) reconnect: 2000, // интервал переподключения в мс (по умолчанию: 1000) }); ``` -------------------------------- ### constructor(params) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Creates an instance of WebSocketJS. The connection is not opened immediately, only configured. Default settings are localhost:81 without SSL and a reconnection interval of 1000 ms. ```APIDOC ## constructor(params) ### Description Creates an instance of WebSocketJS. The connection is not opened immediately, only configured. Default settings are localhost:81 without SSL and a reconnection interval of 1000 ms. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (object) - Optional - Configuration object for the WebSocket connection. - **ip** (string) - Server address (default: "localhost"). - **port** (number) - Port number (default: 81). - **proto** (string) - WebSocket subprotocol (default: undefined). - **secure** (boolean) - Use wss:// (default: false). - **reconnect** (number) - Reconnection interval in ms (default: 1000). ### Request Example ```javascript // Minimal configuration (uses default parameters) const ws = new WebSocketJS(); // Full configuration const ws = new WebSocketJS({ ip: '192.168.1.100', port: 81, proto: 'esp', secure: false, reconnect: 2000 }); ``` ### Response None ``` -------------------------------- ### Event Handlers Source: https://github.com/gyverlibs/websocket.js/blob/main/README.md Set up callback functions to handle various WebSocket events. ```APIDOC ## Event Handlers ### Description These methods allow you to register callback functions for different WebSocket events. ### Methods - **`onbin(callback)`**: Registers a callback for binary data reception. - **`ontext(callback)`**: Registers a callback for text data reception. - **`onopen():`**: Callback function executed when the connection is opened. - **`onclose():`**: Callback function executed when the connection is closed. - **`onchange(callback)`**: Callback function executed when the connection status changes. - **`onerror(callback)`**: Callback function executed when an error occurs. ``` -------------------------------- ### onopen() Source: https://context7.com/gyverlibs/websocket.js/llms.txt Callback function that is invoked upon successful establishment of the WebSocket connection. ```APIDOC ## onopen() ### Description Callback function invoked upon successful establishment of the WebSocket connection. Override this to perform actions immediately after connection. ### Method Signature `onopen()` ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onopen = () => { console.log('Connection established!'); ws.sendText('init'); // immediately send an initialization message }; ws.open(); ``` ``` -------------------------------- ### Websocket.js API Methods Source: https://github.com/gyverlibs/websocket.js/blob/main/README.md Overview of available methods for initializing, configuring, and interacting with WebSocket connections. Includes event handlers and sending data. ```javascript constructor(params = {}); config(params = {}); // ip: "localhost" // port: 81 // proto: "" // secure: false // reconnect: 1000 onbin(b); ontext(t); onopen(): onclose(): onchange(s): onerror(e); opened(); open(); close(); sendBin(data); sendText(text); ``` -------------------------------- ### open() Source: https://context7.com/gyverlibs/websocket.js/llms.txt Opens the WebSocket connection and enables automatic reconnection. If the connection is already in the `CONNECTING` or `OPEN` state, a new connection will not be established. If the connection is lost, the client will automatically attempt to reconnect at the interval specified in `reconnect`. ```APIDOC ## open() ### Description Opens the WebSocket connection and enables automatic reconnection. If the connection is already in the `CONNECTING` or `OPEN` state, a new connection will not be established. If the connection is lost, the client will automatically attempt to reconnect at the interval specified in `reconnect`. ### Method `open` ### Parameters None ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, reconnect: 1000 }); ws.open(); // => Establishes connection: ws://192.168.1.54:81/ // => On disconnection, automatically reconnects every 1000 ms ``` ### Response None ``` -------------------------------- ### opened() Source: https://context7.com/gyverlibs/websocket.js/llms.txt Checks the connection status. Returns `true` if the WebSocket connection is currently open (`readyState === OPEN`), otherwise returns `false`. Used for safe checks before sending data. ```APIDOC ## opened() ### Description Checks the connection status. Returns `true` if the WebSocket connection is currently open (`readyState === OPEN`), otherwise returns `false`. Used for safe checks before sending data. ### Method `opened` ### Parameters None ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.open(); setInterval(() => { if (ws.opened()) { ws.sendText('ping'); console.log('Message sent'); } else { console.log('Connection not active, waiting...'); } }, 2000); ``` ### Response - **return value** (boolean) - `true` if the connection is open, `false` otherwise. ``` -------------------------------- ### onchange(state) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Callback function that is invoked whenever the connection state changes. It receives a string representing the new state. ```APIDOC ## onchange(state) ### Description Callback function invoked on every connection state change. Receives a string from the static enumeration `WebSocketJS.State`: `"closed"`, `"opening"`, `"open"`, `"closing"`. ### Method Signature `onchange(state)` ### Parameters #### Path Parameters - **state** (string) - Required - The new state of the connection (`"closed"`, `"opening"`, `"open"`, `"closing"`). ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onchange = (state) => { console.log('State changed:', state); // => "opening" -> "open" -> "closing" -> "closed" const statusEl = document.getElementById('status'); switch (state) { case WebSocketJS.State.Open: statusEl.textContent = 'Connected'; break; case WebSocketJS.State.Closed: statusEl.textContent = 'Disconnected'; break; case WebSocketJS.State.Opening: statusEl.textContent = 'Connecting...'; break; case WebSocketJS.State.Closing: statusEl.textContent = 'Disconnecting...'; break; } }; ws.open(); ``` ``` -------------------------------- ### Open WebSocket Connection Source: https://context7.com/gyverlibs/websocket.js/llms.txt Initiate a WebSocket connection and enable automatic reconnection. If the connection is already in progress or open, this method will not re-initiate. The client will attempt to reconnect at the specified interval if the connection is lost. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, reconnect: 1000 }); ws.open(); // => Устанавливает соединение: ws://192.168.1.54:81/ // => При обрыве — автоматически переподключается каждые 1000 мс ``` -------------------------------- ### Connection Management Source: https://github.com/gyverlibs/websocket.js/blob/main/README.md Methods to control the WebSocket connection state. ```APIDOC ## Connection Management ### Description Provides methods to manage the WebSocket connection lifecycle. ### Methods - **`opened()`**: Returns a boolean indicating if the connection is currently open. - **`open()`**: Attempts to establish a WebSocket connection. - **`close()`**: Closes the WebSocket connection. ``` -------------------------------- ### onbin(b) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Callback function that is invoked when binary data is received. The data is provided as an ArrayBuffer. ```APIDOC ## onbin(b) ### Description Callback function invoked when binary data is received. The data type is `ArrayBuffer` (set via `binaryType = "arraybuffer"` within the library). ### Method Signature `onbin(buffer)` ### Parameters #### Path Parameters - **buffer** (ArrayBuffer) - Required - The received binary data. ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, proto: 'esp' }); ws.onbin = (buffer) => { const bytes = new Uint8Array(buffer); console.log('Received bytes:', bytes); // => Received bytes: Uint8Array [12, 34, 56] }; ws.open(); ``` ``` -------------------------------- ### sendBin(data) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Sends binary data through the WebSocket connection. This method is useful for transmitting structured byte data, such as commands to microcontrollers. The call is ignored if the connection is closed. ```APIDOC ## sendBin(data) ### Description Sends binary data (e.g., `Uint8Array`, `ArrayBuffer`) over WebSocket. Ignores the call if the connection is closed. Used for transmitting structured byte data, like commands to microcontrollers. ### Method Signature `sendBin(data)` ### Parameters #### Path Parameters - **data** (Uint8Array | ArrayBuffer) - Required - The binary data to send. ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, proto: 'esp' }); ws.open(); let i = 0; document.getElementById('sendb_b').onclick = () => { const payload = new Uint8Array([i++, i++, i++]); ws.sendBin(payload); // => Server receives a binary packet of 3 bytes: [0, 1, 2], [3, 4, 5], ... }; ``` ``` -------------------------------- ### Send Binary Data with WebSocket.js Source: https://context7.com/gyverlibs/websocket.js/llms.txt Use `sendBin` to transmit binary data like Uint8Array or ArrayBuffer. The call is ignored if the connection is closed. This is useful for sending structured byte data, such as commands to a microcontroller. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, proto: 'esp' }); ws.open(); let i = 0; document.getElementById('sendb_b').onclick = () => { const payload = new Uint8Array([i++, i++, i++]); ws.sendBin(payload); // => Сервер получает бинарный пакет из 3 байт: [0, 1, 2], [3, 4, 5], ... }; ``` -------------------------------- ### Sending Data Source: https://github.com/gyverlibs/websocket.js/blob/main/README.md Methods for sending binary and text data over the WebSocket connection. ```APIDOC ## Sending Data ### Description Methods to send data to the connected WebSocket server. ### Methods - **`sendBin(data)`**: Sends binary data. - **Parameters**: - **data** (Blob | ArrayBuffer | Buffer) - The binary data to send. - **`sendText(text)`**: Sends text data. - **Parameters**: - **text** (string) - The text data to send. ``` -------------------------------- ### WebSocketJS.State Source: https://context7.com/gyverlibs/websocket.js/llms.txt A static object containing constants for connection states, used in conjunction with the `onchange` callback. ```APIDOC ## WebSocketJS.State ### Description Static object of the class with state constants. Used in conjunction with the `onchange` callback. ### Properties - **Closed** (string) - Represents the closed state. - **Opening** (string) - Represents the opening state. - **Open** (string) - Represents the open state. - **Closing** (string) - Represents the closing state. ### Request Example ```javascript console.log(WebSocketJS.State); // => { // Closed: 'closed', // Opening: 'opening', // Open: 'open', // Closing: 'closing', // } const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onchange = (s) => { if (s === WebSocketJS.State.Open) { console.log('Ready to send data'); } }; ws.open(); ``` ``` -------------------------------- ### Check WebSocket Connection Status Source: https://context7.com/gyverlibs/websocket.js/llms.txt Verify if the WebSocket connection is currently open (`readyState === OPEN`). This check is crucial for ensuring data is sent only when the connection is active. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.open(); setInterval(() => { if (ws.opened()) { ws.sendText('ping'); console.log('Сообщение отправлено'); } else { console.log('Соединение не активно, ожидание...'); } }, 2000); ``` -------------------------------- ### sendText(text) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Sends a string message over the WebSocket. If the connection is not open, the call is ignored due to an internal check using `opened()`. ```APIDOC ## sendText(text) ### Description Sends a string message over the WebSocket. If the connection is not open, the call is ignored due to an internal check using `opened()`. ### Method `sendText` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **text** (string) - The text message to send. ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.open(); let counter = 0; document.getElementById('sendt_b').onclick = () => { ws.sendText('Hello ' + counter++); // => Server receives the string: "Hello 0", "Hello 1", ... }; ``` ### Response None ``` -------------------------------- ### onclose() Source: https://context7.com/gyverlibs/websocket.js/llms.txt Callback function that is invoked when the WebSocket connection is closed, including cases of lost connection before reconnection. ```APIDOC ## onclose() ### Description Callback function invoked when the connection is closed (including loss of connection before reconnection). Override this to handle disconnection events. ### Method Signature `onclose()` ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81, reconnect: 1000 }); ws.onclose = () => { console.log('Connection closed, waiting for reconnection...'); document.getElementById('status').textContent = 'Disconnected'; }; ws.open(); ``` ``` -------------------------------- ### close() Source: https://context7.com/gyverlibs/websocket.js/llms.txt Properly closes the WebSocket connection and disables automatic reconnection. After calling `close()`, the client will not attempt to restore the connection on its own. ```APIDOC ## close() ### Description Properly closes the WebSocket connection and disables automatic reconnection. After calling `close()`, the client will not attempt to restore the connection on its own. ### Method `close` ### Parameters None ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.open(); // Close connection on button click document.getElementById('close_b').onclick = () => { ws.close(); // => Connection closed, auto-reconnect disabled }; ``` ### Response None ``` -------------------------------- ### ontext(t) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Callback function that is invoked when a text message is received from the server. It is a placeholder for custom message handling logic. ```APIDOC ## ontext(t) ### Description Callback function invoked when a text message is received from the server. By default, it's an empty function. Override this to handle incoming text messages. ### Method Signature `ontext(text)` ### Parameters #### Path Parameters - **text** (string) - Required - The received text message. ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.ontext = (text) => { console.log('Received text:', text); // => Received text: Hello from server document.getElementById('output').textContent = text; }; ws.open(); ``` ``` -------------------------------- ### Send Text Message via WebSocket Source: https://context7.com/gyverlibs/websocket.js/llms.txt Transmit a string message over the WebSocket. If the connection is not open, the call is ignored due to an internal check using `opened()`. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.open(); let counter = 0; document.getElementById('sendt_b').onclick = () => { ws.sendText('Hello ' + counter++); // => Сервер получает строку: "Hello 0", "Hello 1", ... }; ``` -------------------------------- ### onerror(e) Source: https://context7.com/gyverlibs/websocket.js/llms.txt Callback function that is invoked when a WebSocket error occurs. It receives an error string. ```APIDOC ## onerror(e) ### Description Callback function invoked when a WebSocket error occurs. Receives the string `'[WS] Error'`. ### Method Signature `onerror(err)` ### Parameters #### Path Parameters - **err** (string) - Required - The error message string. ### Request Example ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.onerror = (err) => { console.error('WebSocket Error:', err); // => WebSocket Error: [WS] Error }; ws.open(); ``` ``` -------------------------------- ### Close WebSocket Connection Source: https://context7.com/gyverlibs/websocket.js/llms.txt Gracefully close the WebSocket connection and disable automatic reconnection. After calling `close()`, the client will not attempt to re-establish the connection. ```javascript const ws = new WebSocketJS({ ip: '192.168.1.54', port: 81 }); ws.open(); // Закрытие соединения по кнопке document.getElementById('close_b').onclick = () => { ws.close(); // => Соединение закрыто, автопереподключение отключено }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.