TCP sockets
In PandJS, std:net
module provides an asynchronous network API for creating stream-based TCP connections.
TCP echo client
In this code below, client will wait for data from the server and will send this data back.
import { Socket } from 'std:net';
const socket = new Socket();
socket.ondata = (chunk) => { console.log(chunk.toString('utf8')); socket.write(chunk);}
socket.onerror = (err) => { console.log("Got error:", err);}
socket.onclose = () => { console.log("connection closed?", socket.destroyed);}
await socket.connect('127.0.0.1', 8000);
TCP echo server
import { Server } from 'std:net';
const server = new Server();
server.onconnection = function(socket) { socket.ondata = (chunk) => { console.log(chunk.toString('utf8')); socket.write(chunk); socket.shutdown(); };
socket.onerror = (err) => { console.log(err); }
socket.onclose = () => { console.log("connection closed"); };}
server.listen(5000);console.log(`Starting server on port: ${server.port}`);
Closing TCP connections
There is 2 ways to close connection:
- Graceful with
socket.shutdown
- prefered way of closing connections.socket.shutdown(); - Aggresive with
socket.destroy
- useful during errors and timeouts.socket.destroy();