forked from zeromq/zeromq.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.stream.js
75 lines (61 loc) · 2.49 KB
/
socket.stream.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
var zmq = require('..')
, http = require('http')
, should = require('should')
, semver = require('semver');
describe('socket.stream', function(){
it('should support a stream socket type', function (done){
// socket stream type API after libzmq4+, target > 4.0.0
// v4.1.3's stream socket is a little buggy, let's exclude it for now
if (semver.gte(zmq.version, '4.0.0') && semver.lt(zmq.version, '4.1.3')) {
var stream = zmq.socket('stream');
stream.on('message', function (id,msg){
msg.should.be.an.instanceof(Buffer);
var raw_header = String(msg).split('\r\n');
var method = raw_header[0].split(' ')[0];
method.should.equal('GET');
//finding an HTTP GET method, prepare HTTP response for TCP socket
var httpProtocolString = 'HTTP/1.0 200 OK\r\n' //status code
+ 'Content-Type: text/html\r\n' //headers
+ '\r\n'
+ '<!DOCTYPE html>' //response body
+ '<head>' //make it xml, json, html or something else
+ '<meta charset="UTF-8">'
+ '</head>'
+ '<body>'
+'<p>derpin over protocols</p>'
+ '</body>'
+'</html>'
//zmq streaming prefixed by envelope's routing identifier
stream.send([id,httpProtocolString]);
});
var addr = '127.0.0.1:5513';
stream.bind('tcp://'+addr, function (error) {
if (error) throw error;
//send non-peer request to zmq, like an http GET method with URI path
http.get('http://'+addr+'/aRandomRequestPath', function (httpMsg){
//msg should now be a node readable stream as the good lord intended
if (semver.gte(process.versions.node, '0.11.0')){
httpMsg.socket._readableState.reading.should.be.false
} else {
if(semver.gte(process.versions.node, '0.10.0')){
httpMsg.socket._readableState.reading.should.be.true
}
}
//conventional node streams emit data events to process zmq stream response
httpMsg.on('data',function (msg){
msg.should.be.an.instanceof(Buffer);
String(msg).should.equal('<!DOCTYPE html><head><meta charset="UTF-8"></head>'
+'<body>'
+'<p>derpin over protocols</p>'
+'</body>'
+'</html>');
done();
});
});
});
} else {
done();
return console.warn('stream socket type in libzmq v4+');
}
});
});