Name: tcp-base
Owner: node_modules
Description: TCP client base
Created: 2016-09-16 08:20:09.0
Updated: 2018-05-03 11:46:33.0
Pushed: 2017-12-01 06:39:18.0
Homepage: null
Size: 31
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
A base class for tcp client with basic functions
m install tcp-base --save
Node.js >= 6.0.0 required
A quick guide to implement a tcp echo client
Client:
strict';
t TCPBase = require('tcp-base');
Simple Protocol:
(4B): request id
(4B): body length
------------------------------
body data
s Client extends TCPBase {
tHeader() {
return this.read(8);
tBodyLength(header) {
return header.readInt32BE(4);
code(body, header) {
return {
id: header.readInt32BE(0),
data: body,
};
heartbeat packet
t heartBeatPacket() {
return new Buffer([ 255, 255, 255, 255, 0, 0, 0, 0 ]);
t client = new Client({
st: '127.0.0.1',
rt: 8080,
t body = new Buffer('hello');
t data = new Buffer(8 + body.length);
.writeInt32BE(1, 0);
.writeInt32BE(body.length, 4);
.copy(data, 8, 0);
nt.send({
: 1,
ta,
meout: 5000,
err, res) => {
(err) {
console.error(err);
nsole.log(res.toString()); // should echo 'hello'
Server:
strict';
t net = require('net');
t server = net.createServer(socket => {
t header;
t bodyLen;
nction readPacket() {
if (bodyLen == null) {
header = socket.read(8);
if (!header) {
return false;
}
bodyLen = header.readInt32BE(4);
}
if (bodyLen === 0) {
socket.write(header);
} else {
const body = socket.read(bodyLen);
if (!body) {
return false;
}
socket.write(Buffer.concat([ header, body ]));
}
bodyLen = null;
return true;
cket.on('readable', () => {
try {
let remaining = false;
do {
remaining = readPacket();
}
while (remaining);
} catch (err) {
console.error(err);
}
;
er.listen(8080);