-
Notifications
You must be signed in to change notification settings - Fork 1
/
transport.ts
34 lines (27 loc) · 856 Bytes
/
transport.ts
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
import WebSocket from 'ws'
import { Subject, BehaviorSubject } from 'rxjs'
export default <S, R>(initialState: S) => {
const receive = new Subject<R>()
const send = new BehaviorSubject<S>(initialState)
const server = new WebSocket.Server({ port: 8080 })
console.log('websokcet server started')
server.on('connection', socket => {
console.log('total clients:', server.clients.size)
socket.on('close', () => {
console.log('total clients:', server.clients.size)
})
socket.on('message', message => {
const data = JSON.parse(message.toString())
console.log('received:', data)
receive.next(data)
})
send.subscribe({
next: data => {
console.log('send:', data)
const message = JSON.stringify(data)
socket.send(message)
},
})
})
return { receive, send }
}