Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"image": "mcr.microsoft.com/devcontainers/universal:2",
"features": {
"ghcr.io/nordcominc/devcontainer-features/android-sdk:1": {}
}
}
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"cordova-plugin-advanced-http": {
"ANDROIDBLACKLISTSECURESOCKETPROTOCOLS": "SSLv3,TLSv1"
},
"cordova-plugin-websocket": {},
"com.foxdebug.acode.exec": {}
},
"platforms": [
Expand Down Expand Up @@ -76,6 +77,7 @@
"cordova-plugin-server": "file:src/plugins/server",
"cordova-plugin-sftp": "file:src/plugins/sftp",
"cordova-plugin-system": "file:src/plugins/system",
"cordova-plugin-websocket": "file:src/plugins/websocket",
"css-loader": "^7.1.2",
"mini-css-extract-plugin": "^2.9.0",
"path-browserify": "^1.0.1",
Expand Down
135 changes: 135 additions & 0 deletions src/plugins/websocket/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Cordova Plugin: OkHttp WebSocket

A Cordova plugin that uses [OkHttp](https://square.github.io/okhttp/) to provide WebSocket support in your Cordova app.
It aims to mimic the [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) in JavaScript, with additional features.

## Features

* ✅ WebSocket API-like interface
* ✅ Event support: `onopen`, `onmessage`, `onerror`, `onclose`
* ✅ `extensions` and `readyState` properties
* ✅ `listClients()` to list active connections
* ✅ Support for protocols
* ✅ Support for Custom Headers.
* ✅ Compatible with Cordova for Android

---

## Usage

### Import

```javascript
const WebSocketPlugin = cordova.websocket;
```

### Connect to WebSocket

```javascript
WebSocketPlugin.connect("wss://example.com/socket", ["protocol1", "protocol2"], headers)
.then(ws => {
ws.onopen = (e) => console.log("Connected!", e);
ws.onmessage = (e) => console.log("Message:", e.data);
ws.onerror = (e) => console.error("Error:", e);
ws.onclose = (e) => console.log("Closed:", e);

ws.send("Hello from Cordova!");
ws.close();
})
.catch(err => console.error("WebSocket connection failed:", err));
```

---

## API Reference

### Methods

* `WebSocketPlugin.connect(url, protocols, headers, binaryType)`
* Connects to a WebSocket server.
* `url`: The WebSocket server URL.
* `protocols`: (Optional) An array of subprotocol strings.
* `headers`: (Optional) Custom headers as key-value pairs.
* `binaryType`: (Optional) Initial binary type setting.
* **Returns:** A Promise that resolves to a `WebSocketInstance`.

* `WebSocketPlugin.listClients()`
* Lists all stored webSocket instance IDs.
* **Returns:** `Promise` that resolves to an array of `instanceId` strings.

* `WebSocketPlugin.send(instanceId, message, binary)`
* Sends a message to the server using an instance ID.
* `instanceId`: The ID of the WebSocket instance.
* `message`: The message to send (string or ArrayBuffer/ArrayBufferView).
* `binary`: (Optional) Whether to send the message as binary, accepts `boolean`
* **Returns:** `Promise` that resolves when the message is sent.

* `WebSocketPlugin.close(instanceId, code, reason)`
* same as `WebSocketInstance.close(code, reason)` but needs `instanceId`.
* **Returns:** `Promise` that resolves.

### WebSocketInstance Methods

* `WebSocketInstance.send(message, binary)`
* Sends a message to the server.
* `message`: The message to send (string or ArrayBuffer/ArrayBufferView).
* `binary`: (Optional) Whether to send the message as binary. accepts `boolean`
* Throws an error if the connection is not open.

* `WebSocketInstance.close(code, reason)`
* Closes the connection.
* `code`: (Optional) If unspecified, a close code for the connection is automatically set: to 1000 for a normal closure, or otherwise to [another standard value in the range 1001-1015](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1) that indicates the actual reason the connection was closed.
* `reason`: A string providing a [custom WebSocket connection close reason](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6) (a concise human-readable prose explanation for the closure). The value must be no longer than 123 bytes (encoded in UTF-8).

---

### Properties of `WebSocketInstance`

* `onopen`: Event listener for connection open.
* `onmessage`: Event listener for messages received.
* `onclose`: Event listener for connection close.
* `onerror`: Event listener for errors.
* `readyState`: (number) The state of the connection.
* 0 (`CONNECTING`): Socket created, not yet open.
* 1 (`OPEN`): Connection is open and ready.
* 2 (`CLOSING`): Connection is closing.
* 3 (`CLOSED`): Connection is closed or couldn't be opened.
* `extensions`: (string) Extensions negotiated by the server.
* `binaryType`: (string) Type of binary data to use ('arraybuffer' or '' (binary payload returned as strings.)).
* `url`: (string) The WebSocket server URL.
* `instanceId`: (string) Unique identifier for this WebSocket instance.

### Event Handling

`WebSocketInstance` extends `EventTarget`, providing standard event handling methods:

* `addEventListener(type, listener)`: Registers an event listener.
* `removeEventListener(type, listener)`: Removes an event listener.
* `dispatchEvent(event)`: Dispatches an event to the object.

Example of using event listeners:
```javascript
const ws = await WebSocketPlugin.connect("wss://example.com/socket");

// Using on* properties
ws.onmessage = (event) => console.log("Message:", event.data);

// Using addEventListener
ws.addEventListener('message', (event) => console.log("Message:", event.data));
```

### Constants

* `WebSocketInstance.CONNECTING`: 0
* `WebSocketInstance.OPEN`: 1
* `WebSocketInstance.CLOSING`: 2
* `WebSocketInstance.CLOSED`: 3

---

## Notes

* Only supported on Android (via OkHttp).
* Make sure to handle connection lifecycle properly (close sockets when done).
* `listClients()` is useful for debugging and management.
---
22 changes: 22 additions & 0 deletions src/plugins/websocket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "cordova-plugin-websocket",
"version": "0.0.1",
"description": "This cordova plugin is created to use WebSocket (client) in web/js.",
"cordova": {
"id": "cordova-plugin-websocket",
"platforms": [
"android"
]
},
"keywords": [
"cordova",
"websocket",
"cordova-android",
"ws"
],
"author": "Acode-Foundation (created by UnschooledGamer)",
"license": "Apache-2.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
}
}
21 changes: 21 additions & 0 deletions src/plugins/websocket/plugin.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin id="cordova-plugin-websocket" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0">
<name>cordova-plugin-websocket</name>
<description>Cordova Websocket</description>
<license>MIT</license>
Copy link

Copilot AI May 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The license in plugin.xml is set to MIT, but package.json specifies Apache-2.0. Please align the license entries to avoid confusion for consumers.

Copilot uses AI. Check for mistakes.
<keywords>cordova,ws,WebSocket</keywords>
<js-module src="www/websocket.js" name="WebSocket">
<clobbers target="cordova.websocket" />
</js-module>

<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="WebSocketPlugin">
<param name="android-package" value="com.foxdebug.websocket.WebSocketPlugin" />
</feature>
</config-file>
<source-file src="src/android/WebSocketPlugin.java" target-dir="src/com/foxdebug/websocket" />
<source-file src="src/android/WebSocketInstance.java" target-dir="src/com/foxdebug/websocket" />
<framework src="com.squareup.okhttp3:okhttp:4.12.0" />
</platform>
</plugin>
Loading