socket-promise
v1.0.1
Published
This package extends default NodeJS sockets adding promises support for connect and receive.
Downloads
6
Readme
Socket Promise
Socket Promise extends NodeJS default Socket class and add's promise support.
API
Client
writeInChunks(data, chunkLength)
- Split and write data in chunks
conn(ip, port, [timeout])
- (Promise) Connect to specified ip and port
recv([contains, timeout])
- (Promise) Receive data
SocketPromise.wrapper(socket)
- Implements SocketPromise functions in a default socket instance
Server
SocketPromise.createServer()
- Create tcp server
accept()
- (Promise) Accept new connection
Also including everything in https://nodejs.org/api/net.html
Installation
npm i -S socket-promise
Client Example
const SocketPromise = require('socket-promise');
(async () => {
const socket = new SocketPromise();
try {
const milisec = await socket.conn('123.123.123.123', 1337, 5000);
console.log(`Connected for ${milisec} miliseconds`);
socket.write('hello world'); // send
const response1 = await socket.recv(); // receive
console.log(`Received ${response1.toString()}`);
// receive until response contains string 'end_of_message'
const response2 = await socket.recv('end_of_message');
console.log(`Received ${response2.toString()}`);
} catch (err) {
if (err instanceof SocketPromise.errors.Timeout) {
console.log('Connect Timeout'); // after 5 seconds
} else if (err instanceof SocketPromise.errors.Closed) {
console.log('Connection Closed');
} else {
console.log(err);
}
}
})();
Server Example
const SocketPromise = require('socket-promise');
(async () => {
const server = SocketPromise.createServer();
server.listen(1234, '0.0.0.0');
let client;
let counter = 1;
try {
while (client = await server.accept()) {
console.log(`client ${counter}`);
counter++;
// do something with the client
}
} catch (err) {
if (err instanceof SocketPromise.errors.Closed) {
console.log('Connection Closed');
} else {
console.log(err);
}
}
})();