💡

【Node.js】TCP サーバーとクライアント

2024/09/29に公開

公式マニュアルにそのまま動くコードのサンプルが記載されているのでやってみた

server.js
// https://nodejs.org/api/net.html#netcreateserveroptions-connectionlistener
const net = require('node:net');
const server = net.createServer((c) => {
  // 'connection' listener.
  console.log('client connected');
  c.on('end', () => {
    console.log('client disconnected');
  });
  c.write('hello\r\n');
  c.pipe(c);
});
server.on('error', (err) => {
  throw err;
});
server.listen(5000, () => {
  console.log('server bound');
});
client.js
// https://nodejs.org/api/net.html#netcreateconnectionoptions-connectlistener
const net = require('node:net');
const client = net.createConnection({ port: 5000 }, () => {
  // 'connect' listener.
  console.log('connected to server!');
  client.write('world!\r\n');
});
client.on('data', (data) => {
  console.log(data.toString());
  client.end();
});
client.on('end', () => {
  console.log('disconnected from server');
});

少し書き換えて HTTP/1 サーバーとクライアントにしてみる

server.js
const net = require('node:net');

const server = net.createServer((c) => {
  msg = [
    'HTTP/1.1 200 OK',
    'Content-Length: 12',
    'Connection: close',
    'Content-Type: text/html; charset=UTF-8',
    '',
    'Hello world!'
  ].join('\r\n');

  c.write(msg);
});
server.on('error', (err) => {
  throw err;
});
server.listen(5000, () => {
  console.log('starting server');
});
client.js
const net = require('node:net');

const client = net.createConnection({ port: 5000 }, () => {
  msg = [
    'GET / HTTP/1.1',
    'Host: localhost',
    'Connection: keep-alive'
  ].join('\r\n');
  client.write(msg);
});

client.on('data', (data) => {
  console.log(data.toString());
  client.destroy();
});

Discussion