Created
October 8, 2015 14:28
-
-
Save AndreasMadsen/a90591087368fd42496b to your computer and use it in GitHub Desktop.
AsyncWrap tcp events example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const net = require('net'); | |
const server = net.createServer(function (socket) { | |
socket.write('hallo world'); | |
}); | |
server.listen('127.0.0.1', 8080); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const asyncWrap = process.binding('async_wrap'); | |
const TCP = process.binding('tcp_wrap').TCP; | |
const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; | |
// Log AsyncWrap events | |
function init() { | |
process._rawDebug('init // ' + this.constructor.name); | |
} | |
function before() { | |
process._rawDebug('before // ' + this.constructor.name); | |
} | |
function after() { | |
process._rawDebug('after // ' + this.constructor.name); | |
} | |
asyncWrap.setupHooks(init, before, after); | |
asyncWrap.enable(); | |
// Set up very basic tcp socket | |
function tcpSocket(address, port, oncomplete, onread) { | |
const socket = new TCP(); | |
socket.onread = onread; | |
const req = new TCPConnectWrap(); | |
req.oncomplete = function () { | |
socket.readStart(); | |
oncomplete(); | |
}; | |
req.address = address; | |
req.port = port; | |
socket.connect(req, address, port); | |
} | |
// Detect the ticks | |
let detectTicks = true; | |
process.nextTick(function recursive() { | |
process._rawDebug('=== tick ==='); | |
if (detectTicks) setImmediate(recursive); | |
}); | |
// Create socket | |
tcpSocket( | |
'127.0.0.1', 8080, | |
() => process._rawDebug('complete'), | |
() => {detectTicks = false; process._rawDebug('read')} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment