4
3

More than 5 years have passed since last update.

Socket.ioでコンソールベースのチャットを作ってみる

Posted at

Socket.IOの勉強がてら、よくある簡単なチャットを作ってみた。
Socket.IOのドキュメントや色々な記事ではブラウザベースのチャットの例が多いが、今回はコンソールベースのチャットを作った。

terminal.png

サーバの実装

const io = require('socket.io')();
io.listen(3000);

io.on('connection', (socket) => {
  console.log(`connected, id: ${socket.id}`);

  socket.on('chat message', (user, message) => {
    data = `${message} from ${user}`;
    console.log(data);
    socket.broadcast.emit('chat message', data);
  });

  socket.on('disconnect', () => {
    console.log(`disconnected, id: ${socket.id}`);
  });
});

クライアントの実装

const readline = require('readline');
const socket = require('socket.io-client')('http://localhost:3000');

const user = process.argv[2];

rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('');

rl.on('line', (line) => {
  socket.emit('chat message', user, line);
})
.on('close', () => {
  process.exit(0);
});

socket.on('connect', () => {
  console.log(`connected, id: ${socket.id}`);
});

socket.on('chat message', (data) => {
  console.log(data);
});

socket.on('error', (err) => {
  console.log('Error:', err);
});

socket.on('disconnect', () => {
  console.log('disconnected');
});

サーバ起動

$ node index.js

クライアント起動

$ node client.js $USER_NAME

サーバはメッセージをブロードキャストするようにしているので、クライアントを複数起動すれば、チャットみたいなことができる。

4
3
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
4
3