0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

node.jsでTCP通信 (serverからの送信内容をclientでエコーバックする)

Last updated at Posted at 2021-01-15

node.jsでTCP通信をする方法を調べていると

  1. cilent側で文字を入力して
  2. それをserver側で折り返して
  3. それをclient側でコンソールに表示

というサンプルが山ほど見つかるのですが、

  1. server側で文字を入力して
  2. それをclient側で折り返して
  3. それをserver側でコンソールに表示

という例が見つからなかったので、書いてみました。

server.js

var net = require('net');

var server = net.createServer(conn => {
    console.log('connected.');
    
    conn.on('data', data => {
        console.log('server-> ' + data);
    });
    
    conn.on('close', () => {
        console.log('closed');
    });
    
    process.stdin.resume()
    process.stdin.on('data', data => {
        conn.write(data)
    });

}).listen(3000);

console.log('listening on port 3000');

client.js

var net = require('net');

var client = new net.Socket();
client.setEncoding('utf8');

client.connect('3000', 'localhost', () => {
    console.log('connected');
});

client.on('data', data => {
    console.log('client-> ' + data);
    client.write(data);
});

client.on('close', () => {
    console.log('closed');
});

以上です

参考
https://nodejs.org/api/net.html#net_net_createserver_options_connectionlistener

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?