Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pshihn/sockly
https://github.com/pshihn/sockly
Last synced: 27 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/pshihn/sockly
- Owner: pshihn
- License: mit
- Created: 2019-10-28T00:07:50.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2022-07-20T16:55:59.000Z (over 2 years ago)
- Last Synced: 2024-05-01T15:56:05.388Z (6 months ago)
- Language: TypeScript
- Size: 22.5 KB
- Stars: 70
- Watchers: 3
- Forks: 4
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 🧦🧦 SOCKLY 🧦🧦
Sockly is the easiest way to work with an API over WebSockets or a WebRTC data channel.
Instead of endless message passing, you expose a function or object at one end. At the other end of the connection you simply call the function or use the object properties and mehods.
For example, using a WebSocket, on the server you would:
```javascript
const calculator = {
name: 'Awesome calculator',
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
sockly.expose(calculator, webSocket);
```On the client, simply call that calculator
```javascript
const calculator = sockly.link(webSocket);
await calculator.add(4, 6); // 10
await calculator.subtract(6, 4); // 2
await calculator.name; // Awesome calculator
```## Use Cases
Any time you use WebSockets or RTCDataChannel for p2p applications on the web (Chat app, games, etc).
Yes, one could manually add message handling easily, but it gets really annoying to maintain as more API is added over the socket.
It's just easier to add the new API method and just call it from the client without making any other changes!
*Note: Sockly does not deal with creation/connection/lifecycle of WebSockets or WebRTC channels.*
## Install
Install from npm:
```
npm install --save sockly
```
ES6 import:
```
import {link, expose} from 'sockly'
```Or using pika in the browser
```
import * as sockly from 'https://cdn.pika.dev/sockly';
```## Usage
**`expose`** a function or an object
and then **`link`** the exposed object at the other end.
## Examples
See the live version of the calculator example above:
[Socket server code](https://glitch.com/edit/#!/sockly-basic-server)
[Client code](https://glitch.com/edit/#!/sockly-basic-client)
## How does it work
Sockly creates a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) when you `link` a connection. This proxy intercepts property gets/sets, and method calls. The proxy does the underlying message passing with the other end of the socket.
## License
[MIT License](https://github.com/pshihn/sockly/blob/master/LICENSE) (c) [Preet Shihn](https://twitter.com/preetster)