forked from elastic/apm-agent-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrace-ws.js
More file actions
executable file
·52 lines (46 loc) · 1.64 KB
/
trace-ws.js
File metadata and controls
executable file
·52 lines (46 loc) · 1.64 KB
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
#!/usr/bin/env node --unhandled-rejections=strict
/*
* Copyright Elasticsearch B.V. and other contributors where applicable.
* Licensed under the BSD 2-Clause License; you may not use this file except in
* compliance with the BSD 2-Clause License.
*/
// A small example showing Elastic APM tracing of the 'ws' package.
//
// Currently Elastic APM will create a span for `ws.send()` calls.
// For tracing spans to be created, there must be an active transaction.
// Typically, a transaction is automatically started for incoming HTTP
// requests to a Node.js server. However, because this script is not running
// an HTTP server, we manually start transactions in our websocket server and
// client. More details at:
// https://www.elastic.co/guide/en/apm/agent/nodejs/current/custom-transactions.html
const apm = require('../').start({ // elastic-apm-node
serviceName: 'example-trace-ws'
})
const WebSocket = require('ws')
const PORT = 4567
// Server
const wss = new WebSocket.Server({ port: PORT })
wss.on('connection', function (ws) {
ws.on('message', function (message) {
console.log('server on "message": %j', message)
const tserver = apm.startTransaction('tserver')
ws.send('pong')
tserver.end()
})
})
// Client
const ws = new WebSocket('ws://localhost:' + PORT)
ws.on('open', function () {
const tclient = apm.startTransaction('tclient')
console.log('client: send "ping"')
ws.send('ping', function () {
console.log('client: "ping" has been sent')
})
console.log('client: send "ring"')
ws.send('ring')
tclient.end()
})
ws.on('message', function (message) {
console.log('client on "message": %j', message)
wss.close()
})