https://github.com/node-modules/tcp-base
TCP client base
https://github.com/node-modules/tcp-base
Last synced: 11 days ago
JSON representation
TCP client base
- Host: GitHub
- URL: https://github.com/node-modules/tcp-base
- Owner: node-modules
- License: mit
- Created: 2016-09-16T08:20:09.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2023-08-30T14:11:47.000Z (almost 2 years ago)
- Last Synced: 2025-06-08T21:35:51.172Z (16 days ago)
- Language: JavaScript
- Size: 47.9 KB
- Stars: 27
- Watchers: 12
- Forks: 11
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# tcp-base
A base class for tcp client with basic functions
[![NPM version][npm-image]][npm-url]
[](https://github.com/node-modules/tcp-base/actions/workflows/nodejs.yml)
[![Test coverage][codecov-image]][codecov-url]
[![npm download][download-image]][download-url][npm-image]: https://img.shields.io/npm/v/tcp-base.svg?style=flat-square
[npm-url]: https://npmjs.org/package/tcp-base
[codecov-image]: https://codecov.io/gh/node-modules/tcp-base/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/node-modules/tcp-base
[download-image]: https://img.shields.io/npm/dm/tcp-base.svg?style=flat-square
[download-url]: https://npmjs.org/package/tcp-base## Install
```bash
npm install tcp-base --save
```Node.js >= 6.0.0 required
## Usage
A quick guide to implement a tcp echo client
Client:
```js
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:
```js
'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](LICENSE)