Created
December 9, 2014 06:08
-
-
Save dead-horse/ef3f9040f8be4231dfc6 to your computer and use it in GitHub Desktop.
This file contains 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
var Cutter = require('cutter'); | |
var net = require('net'); | |
/** | |
* must return length of head + body | |
*/ | |
function packetLength(data) { | |
return 4 + data.readInt32BE(0); | |
} | |
var cutter = new Cutter(4, packetLength); | |
cutter.on('packet', function(packet) { | |
var serverMsg = parsePacket(packet); | |
console.log('got server message: ', serverMsg); | |
}); | |
var client = net.connect({port: 12345}); | |
client.on('data', function (data) { | |
cutter.emit('data', data); | |
}); | |
client.on('end', function () { | |
console.log('client disconnected'); | |
}); | |
var clientPacket = createPacket('hello server'); | |
client.write(clientPacket); | |
//---------------helpers------------------// | |
function createPacket(msg) { | |
var head = new Buffer(4); | |
var body = new Buffer(msg); | |
// write body's length into head | |
head.writeInt32BE(body.length, 0); | |
// concat head and body | |
return Buffer.concat([head, body]); | |
} | |
function parsePacket(packet) { | |
var head = packet.slice(0, 4); | |
var body = packet.slice(4, packet.length); | |
return body.toString(); | |
} |
This file contains 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
var Cutter = require('cutter'); | |
var net = require('net'); | |
/** | |
* must return length of head + body | |
*/ | |
function packetLength(data) { | |
return 4 + data.readInt32BE(0); | |
} | |
var server = net.createServer(function(socket) { | |
var cutter = new Cutter(4, packetLength); | |
socket.on('data',function(data) { | |
cutter.emit('data', data); | |
}); | |
cutter.on('packet', function(packet) { | |
var clientMsg = parsePacket(packet); | |
console.log('got client message: ', clientMsg); | |
var serverPacket = createPacket('hello client'); | |
socket.write(serverPacket); | |
}); | |
}); | |
server.listen(12345); | |
//---------------helpers------------------// | |
function createPacket(msg) { | |
var head = new Buffer(4); | |
var body = new Buffer(msg); | |
// write body's length into head | |
head.writeInt32BE(body.length, 0); | |
// concat head and body | |
return Buffer.concat([head, body]); | |
} | |
function parsePacket(packet) { | |
var head = packet.slice(0, 4); | |
var body = packet.slice(4, packet.length); | |
return body.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment