forked from geut/fastify-uws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.js
58 lines (51 loc) · 1.26 KB
/
example.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
import fastify from 'fastify'
import { serverFactory, getUws, WebSocketStream } from './src/server.js'
import fastifyUwsPlugin from './src/plugin.js'
const app = fastify({
serverFactory
})
await app.register(fastifyUwsPlugin)
app.addHook('onReady', async () => {
// access to uws app
// eslint-disable-next-line no-unused-vars
const uwsApp = getUws(app)
})
app.websocketServer.on('open', ws => {
console.log('OPEN')
})
app.websocketServer.on('close', ws => {
console.log('CLOSE')
})
app
.route({
method: 'GET',
url: '/',
handler (req, reply) {
return 'hello from http endpoint'
},
uws: {
// cache subscription topics to produce less memory allocations
topics: [
'home/sensors/ligth',
'home/sensors/temp'
]
},
uwsHandler (conn) {
conn.subscribe('home/sensors/temp')
conn.on('message', (message) => {
conn.publish('home/sensors/temp', 'random message')
})
conn.send(JSON.stringify({ hello: 'world' }))
}
})
.get('/stream', { uws: true }, (conn) => {
const stream = new WebSocketStream(conn)
stream.on('data', data => {
console.log('stream data from /stream')
})
})
.listen({
port: 3000
}, (err) => {
err && console.error(err)
})