💡

【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();
});

TLS にも対応させる

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

const options = {
  key: fs.readFileSync('localhost-key.pem'),
  cert: fs.readFileSync('localhost.pem')
};

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

  socket.write(msg);
});

server.on('error', (err) => {
  throw err;
});

server.listen(8000, () => {
  console.log('starting server');
});
client.js
const tls = require('node:tls');

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

client.on('error', (err) => {
  throw err;
});

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

自己署名のサーバーに対してクライアントを使う場合、次のグローベル変数 NODE_TLS_REJECT_UNAUTHORIZED を設定する

export NODE_TLS_REJECT_UNAUTHORIZED=0

もしくはクライアントコードに次の行を追加する

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

Discussion