-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexample.js
52 lines (45 loc) · 1.19 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
import fastify from 'fastify'
import fastifyUwsPlugin from './src/plugin.js'
import { getUws, serverFactory, WebSocketStream } from './src/server.js'
const app = fastify({
serverFactory,
})
await app.register(fastifyUwsPlugin)
app.addHook('onReady', async () => {
// access to uws app
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)
})