Skip to content

Commit bff0560

Browse files
committed
WIP: http client
1 parent 25a4a41 commit bff0560

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"version": "1.0.0",
44
"description": "This is an experiment to compare HTTP vs WebSockets performance using `Nodejs client` <==> `Python server`",
55
"scripts": {
6+
"http-client": "babel-node src/clients/http/http_client.js",
67
"axios-client": "babel-node src/clients/http/axios_client.js",
78
"fetch-client": "babel-node src/clients/http/fetch_client.js"
89
},

src/clients/http/http_client.js

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import http from 'http'
2+
import { host, port, serverUrl, iters } from '../config'
3+
import PerformanceTimer from '../PerformanceTimer'
4+
5+
const reqOptions = {
6+
hostname: host,
7+
port: port,
8+
path: '/hello',
9+
method: 'POST',
10+
headers: { 'Content-Type': 'application/json' }
11+
}
12+
13+
const postData = JSON.stringify({ name: 'Fran' })
14+
15+
// Would be great to have Promise.defer :_(
16+
class Deferred {
17+
resolve = null
18+
reject = null
19+
constructor() {
20+
this.promise = new Promise((resolve, reject) => {
21+
this.resolve = resolve
22+
this.reject = reject
23+
})
24+
}
25+
}
26+
27+
async function request(reqOptions) {
28+
const deferred = new Deferred() // Promise.defer() => not supported
29+
30+
const req = http.request(reqOptions, resp => {
31+
let strData = ''
32+
33+
// A chunk of data has been recieved.
34+
resp.on('data', chunk => strData += chunk)
35+
36+
// The whole response has been received. Print out the result.
37+
resp.on('end', () => {
38+
const data = JSON.parse(strData)
39+
deferred.resolve(data)
40+
})
41+
42+
})
43+
44+
req.on('error', err => {
45+
console.log(err)
46+
deferred.reject(err)
47+
})
48+
49+
req.write(postData)
50+
req.end()
51+
52+
return deferred.promise
53+
}
54+
55+
export async function runTest() {
56+
console.log(`Http client connecting to http://${host}:${port}`)
57+
58+
const timer = new PerformanceTimer()
59+
60+
console.log(`Running test with ${iters} iterations...`)
61+
62+
timer.start()
63+
64+
let i = iters
65+
await (async function asyncLoop() {
66+
const data = await request(serverUrl, reqOptions)
67+
const { hello } = data
68+
console.log(hello)
69+
70+
if (--i === 0) return
71+
await asyncLoop()
72+
})()
73+
74+
timer.end()
75+
}
76+
77+
if (require.main === module) {
78+
runTest()
79+
}

0 commit comments

Comments
 (0)