Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
.DS_Store
.vscode
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,31 @@ conn.on('eventName', data => {
console.log('Received event: ', data.eventName, 'with payload: ', data.payload)
})
```

**Listener for all events**

```javascript

All events will be sent to `message` listener even if there is another listener sent for those events.

conn.on('message', event => {
console.log("onMessage received event: ",event)
})
```

**Send Events**

Only supports sending serialisable objects and strings now.
Binary data support is in progress.

```javascript
conn.send('eventName',{x:0,y:0})
```

**Send Data**

```javascript
conn.sendData('eventName',new Uint8Array())
```

Client for browser is build on top of WebSocket javascript object. TFPSocketsClient provides access to base socket object via `ws` property and can also be initialised with a pre initialised WebSocket instance using:
```javascript
var cleint = new TFPSocketsClient(null, null,initilisedWS)
Expand Down
36 changes: 32 additions & 4 deletions TFPSocketsClient-Browser.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
const isString = s => typeof (s) === 'string' || s instanceof String;

const TFPUtils_packData = (data, eventName) => {
if(eventName.length > 255) {
throw "Event name length should be < 255"
return
}
let enc = new TextEncoder("utf-8");
eventName = enc.encode(eventName)
let header = new Uint8Array([eventName.length, ...eventName])
return new Uint8Array([...header,...data])
}

const TFPUtils_unpackData = unpacked => {
let headerSize = new Uint8Array(unpacked.slice(0,1))[0]
let header = new Uint8Array(unpacked.slice(1,headerSize+1))
let data = new Uint8Array(unpacked.slice(headerSize+1))
let eventName = new TextDecoder('utf-8').decode(header)
return {eventName,payload:data}
}

class TFPSocketsClient {

constructor(url, protocols,cutomws = null) {
Expand Down Expand Up @@ -42,17 +61,18 @@ class TFPSocketsClient {
}
this.ws.binaryType = "arraybuffer"
this.ws.onmessage = (data) => {
var processedEvent;
if (isString(data.data)) {
//handle incomming message
try {
let obj = JSON.parse(data.data);
this.EventStream.emit(obj.eventName, obj)
processedEvent = JSON.parse(data.data);
} catch (e) {
console.log("Message doesn't repect protocol with exception: ", e)
}
} else {
//binary data wip
processedEvent = TFPUtils_unpackData(data.data)
}
this.EventStream.emit(processedEvent.eventName, processedEvent)
this.EventStream.emit('message',processedEvent)
}
}

Expand All @@ -69,6 +89,14 @@ class TFPSocketsClient {
}
}

sendData(event,payload) {
if (this.isOpen) {
this.ws.send(TFPUtils_packData(payload,event))
} else {
console.log("Connection is not opened")
}
}

}

if (typeof module !== 'undefined' && module.exports) {
Expand Down
19 changes: 19 additions & 0 deletions example.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,45 @@ const express = require('express');
const http = require('http');
const url = require('url');
const TFPSockets = require('./index')
const TextEncoder = require('text-encoding').TextEncoder
const TextDecoder = require('text-encoding').TextDecoder


const app = express();


const server = http.createServer(app);

const eventFilter = (event,f) => [event].filter(f);

const TFPServer = new TFPSockets.server(server,["chat"])
TFPServer.on('connection',client => {
client.on('testEvent', data => {
console.log("test event payload: ", data.payload)
client.send('testEventBack',{x:1,y:100})
})

client.on('message',event => {
console.log("onMessage received event: ",event)
})

client.on('dataEvent', event => {
let text = new TextDecoder('utf-8').decode(event.payload)
console.log("received data event with payload ", text)
})

})


const testClient = new TFPSockets.client("ws://localhost:1507",["chat"])
testClient.on('open', event => {
console.log("test client open")
testClient.send('testEvent',{x:10,y:89})
testClient.send('event2',{})

let data = new TextEncoder('utf-8').encode("Hello world as Uint8Array")
testClient.sendData('dataEvent',data);

})

testClient.on('testEventBack', data => {
Expand Down
38 changes: 34 additions & 4 deletions lib/TFPSockets.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
const WebSocket = require('ws')
const TextEncoder = require('text-encoding').TextEncoder
const TextDecoder = require('text-encoding').TextDecoder

const isString = s => typeof (s) === 'string' || s instanceof String;

const TFPUtils_packData = (data, eventName) => {
if(eventName.length > 255) {
throw "Event name length should be < 255"
return
}
let enc = new TextEncoder("utf-8");
eventName = enc.encode(eventName)
let header = new Uint8Array([eventName.length, ...eventName])
return new Uint8Array([...header,...data])
}

const TFPUtils_unpackData = unpacked => {
let headerSize = new Uint8Array(unpacked.slice(0,1))[0]
let header = new Uint8Array(unpacked.slice(1,headerSize+1))
let data = new Uint8Array(unpacked.slice(headerSize+1))
let eventName = new TextDecoder('utf-8').decode(header)
return {eventName,payload:data}
}

class TFPBaseEventStream {
constructor() {
this.EventStream = (function () {
Expand Down Expand Up @@ -49,17 +70,18 @@ class TFPSocketsClient extends TFPBaseEventStream {
this.EventStream.emit('open',event)
})
this.ws.on('message', (data) => {
var processedEvent;
if (isString(data)) {
//handle incomming message
try {
let obj = JSON.parse(data);
this.EventStream.emit(obj.eventName, obj)
processedEvent = JSON.parse(data);
} catch (e) {
console.log("Message doesn't repect protocol with exception: ", e)
}
} else {
//binary data wip
processedEvent = TFPUtils_unpackData(data)
}
this.EventStream.emit(processedEvent.eventName, processedEvent)
this.EventStream.emit('message',processedEvent)
})
this.ws.on('close', () => this.EventStream.emit('close') )
}
Expand All @@ -73,6 +95,14 @@ class TFPSocketsClient extends TFPBaseEventStream {
}
}

sendData(event,payload) {
if (this.isOpen) {
this.ws.send(TFPUtils_packData(payload,event))
} else {
console.log("Connection is not opened")
}
}

}

class TFPSocketsServer extends TFPBaseEventStream {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tfpsockets",
"version": "0.1.0",
"version": "0.2.0",
"description": "Simple event based websockets wrapper",
"main": "index.js",
"scripts": {
Expand All @@ -19,6 +19,7 @@
"license": "MIT",
"dependencies": {
"express": "^4.16.0",
"text-encoding": "^0.6.4",
"ws": "^3.2.0"
}
}