Skip to content

Commit ab02254

Browse files
committed
Updated browser client
1 parent ba8c5c2 commit ab02254

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

TFPSocketsClient-Browser.js

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
11
const isString = s => typeof (s) === 'string' || s instanceof String;
22

3+
const TFPUtils_packData = (data, eventName) => {
4+
if(eventName.length > 255) {
5+
throw "Event name length should be < 255"
6+
return
7+
}
8+
let enc = new TextEncoder("utf-8");
9+
eventName = enc.encode(eventName)
10+
let header = new Uint8Array([eventName.length, ...eventName])
11+
return new Uint8Array([...header,...data])
12+
}
13+
14+
const TFPUtils_unpackData = unpacked => {
15+
let headerSize = new Uint8Array(unpacked.slice(0,1))[0]
16+
let header = new Uint8Array(unpacked.slice(1,headerSize+1))
17+
let data = new Uint8Array(unpacked.slice(headerSize+1))
18+
let eventName = new TextDecoder('utf-8').decode(header)
19+
return {eventName,payload:data}
20+
}
21+
322
class TFPSocketsClient {
423

524
constructor(url, protocols,cutomws = null) {
@@ -42,17 +61,18 @@ class TFPSocketsClient {
4261
}
4362
this.ws.binaryType = "arraybuffer"
4463
this.ws.onmessage = (data) => {
64+
var processedEvent;
4565
if (isString(data.data)) {
46-
//handle incomming message
4766
try {
48-
let obj = JSON.parse(data.data);
49-
this.EventStream.emit(obj.eventName, obj)
67+
processedEvent = JSON.parse(data.data);
5068
} catch (e) {
5169
console.log("Message doesn't repect protocol with exception: ", e)
5270
}
5371
} else {
54-
//binary data wip
72+
processedEvent = TFPUtils_unpackData(data.data)
5573
}
74+
this.EventStream.emit(processedEvent.eventName, processedEvent)
75+
this.EventStream.emit('message',processedEvent)
5676
}
5777
}
5878

@@ -69,6 +89,14 @@ class TFPSocketsClient {
6989
}
7090
}
7191

92+
sendData(event,payload) {
93+
if (this.isOpen) {
94+
this.ws.send(TFPUtils_packData(payload,event))
95+
} else {
96+
console.log("Connection is not opened")
97+
}
98+
}
99+
72100
}
73101

74102
if (typeof module !== 'undefined' && module.exports) {

0 commit comments

Comments
 (0)