forked from whizdummy/react-native-websocket-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (54 loc) · 1.77 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { NativeModules, NativeEventEmitter, Platform } from 'react-native';
import EventEmitter from 'eventemitter3';
import Socket from "./Socket";
const { RNWebsocketServer } = NativeModules;
const nativeEventEmitter = new NativeEventEmitter(NativeModules.RNWebsocketServer);
export default class WebsocketServer extends EventEmitter {
constructor (ipAddress, port = 3770) {
super();
this.started = false;
this.ipAddress = ipAddress;
this.port = port;
this.nativeEventEmitter = nativeEventEmitter;
this.socketMap = {};
this._registerEvents();
}
/**
* Starts websocket server
*/
start () {
if (this.started) return;
this.started = true;
RNWebsocketServer.start(this.ipAddress, this.port);
}
/**
* Stops/closes websocket server
*/
stop () {
this.started = false;
RNWebsocketServer.stop();
}
write(payload) {
RNWebsocketServer.write(payload);
}
_registerEvents() {
console.log('Registering events');
this.nativeEventEmitter.addListener('connection', (evt) => {
this.socketMap[evt.id] = new Socket(evt.id);
this.emit('connection', this.socketMap[evt.id]);
})
this.nativeEventEmitter.addListener('message', (evt) => {
const socket = this.socketMap[evt.id];
if (socket) {
socket.emit('message', Platform.OS === 'ios' ? evt : JSON.parse(evt.payload));
}
})
this.nativeEventEmitter.addListener('disconnected', (evt) => {
const socket = this.socketMap[evt.id];
if (socket) {
socket.emit('disconnected');
delete this.socketMap[evt.id];
}
})
}
}