Socket
Socket
Sign inDemoInstall

tcp-base

Package Overview
Dependencies
9
Maintainers
4
Versions
11
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

tcp-base

A base class for tcp client with basic functions


Version published
Maintainers
4
Weekly downloads
23,263
increased by0.54%
Install size
92.8 kB

Weekly downloads

Readme

Source

tcp-base

A base class for tcp client with basic functions

NPM version Node.js CI Test coverage npm download

Install

npm install tcp-base --save

Node.js >= 6.0.0 required

Usage

A quick guide to implement a tcp echo client

Client:

const TCPBase = require('tcp-base');

/**
 * A Simple Protocol:
 *   (4B): request id
 *   (4B): body length
 *   ------------------------------
 *   body data
 */
class Client extends TCPBase {
  getHeader() {
    return this.read(8);
  }

  getBodyLength(header) {
    return header.readInt32BE(4);
  }

  decode(body, header) {
    return {
      id: header.readInt32BE(0),
      data: body,
    };
  }

  // heartbeat packet
  get heartBeatPacket() {
    return Buffer.from([ 255, 255, 255, 255, 0, 0, 0, 0 ]);
  }
}

const client = new Client({
  host: '127.0.0.1',
  port: 8080,
});

const body = Buffer.from('hello');
const data = Buffer.alloc(8 + body.length);
data.writeInt32BE(1, 0);
data.writeInt32BE(body.length, 4);
body.copy(data, 8, 0);

client.send({
  id: 1,
  data,
  timeout: 5000,
}, (err, res) => {
  if (err) {
    console.error(err);
  }
  console.log(res.toString()); // should echo 'hello'
});

Server:

'use strict';

const net = require('net');

const server = net.createServer(socket => {
  let header;
  let bodyLen;

  function 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;
  }

  socket.on('readable', () => {
    try {
      let remaining = false;
      do {
        remaining = readPacket();
      }
      while (remaining);
    } catch (err) {
      console.error(err);
    }
  });
});
server.listen(8080);

MIT

Keywords

FAQs

Last updated on 30 Aug 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc