node-modules/tcp-base

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

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

tcp-base

A base class for tcp client with basic functions

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Install
m install tcp-base --save

Node.js >= 6.0.0 required

Usage

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);

MIT


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.