socket.ioにおけるroom機能のサンプル(初心者向け)

初心者なので、いろいろ試して挫折した
ここまで検証できたことを記事として作成してみた。
■前提条件
node.js導入済

■検証環境
Windows 10、
VSCode
フォルダーを作成して、
下記の3つファイルをフォルダーに配置、VSCODEでF5をぽっち。

launch.jsonの細かい記述に詳しくないが、
compoundsのところで
記述することで同時にクライアントとサーバーを一緒に起動できる。

```launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Server",
            "program": "${workspaceFolder}/socketIOserver.js",
            "outputCapture": "std"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Client",
            "program": "${workspaceFolder}/socketIOclient.js",
            "outputCapture": "std"
        }, 

    ],
    "compounds": [
        {
            "name": "Server/Client",
            "configurations": ["Server", "Client"],
        }
    ]
}
```


クライアントのサンプル(冗長の記述で悪いが、そのままでわかりやすいかも)

```socketIOclient.js
'use strict'
const io = require('socket.io-client')
//クライアント接続を3つ確立、ただしmultiplex（多重化）はなく、同じソケットを共用する
const socket1 = io('http://localhost:3000')
const socket2 = io('http://localhost:3000') 
const socket3 = io('http://localhost:3000')

//registerUserイベントをトリガーさせ、socket.broadcast.emit(...)の挙動を確認
socket1.emit('registerUser', 'Hoge') 
socket2.emit('registerUser', 'Piyo')
socket3.emit('registerUser', 'Foo')

//各クライアント接続にてのイベントリスナーの動作を定義
socket1.on('entryNotify', message=>  console.log(message)) // hello 
socket1.on('newUserNotify', message => console.log(`socket1 receives ${message}`)) // <registerUser> joined
socket1.on('roomNotify', message =>console.log(`socket1 receives ${message}`))

socket2.on('entryNotify', message=>  console.log(message)) // hello 
socket2.on('newUserNotify', message =>console.log(`socket2 recieves ${message}`)) // <registerUser> joined
socket2.on('roomNotify', message =>console.log( `socket2 receives ${message}`))

socket3.on('entryNotify', message=>  console.log(message)) // hello 
socket3.on('newUserNotify', message =>console.log(`socket3 receives ${message}`)) // <registerUser> joined
socket3.on('roomNotify', message =>console.log( `socket3 receives ${message}`))

//サーバー側のchatイベントをトリガーさせ、io.to(room).emit(...)の挙動を確認
socket1.emit('chat', {'msg': 'Can you hear me?? ', 'room': 'roomA'})
socket1.emit('chat', {'msg': 'Can you hear me?? 2x ', 'room': 'roomA'})
socket1.emit('chat', {'msg': 'Can you hear me?? 3x ', 'room': 'roomA'})

socket2.emit('chat', {'msg': 'Stop spamming!', 'room': 'roomA'})
socket3.emit('chat', {'msg': 'I can hear you!', 'room': 'roomA'})


```

サーバー(別にhttpサーバーで立てなくてもいい　Expressなどでもいい)

```socketIOserver.js
'use strict'
const http = require('http')
const Server = require('socket.io')
const server = http.createServer((req, res) => {}).listen(3000)
//ポート3000でソケットを接続させることにする
const io = Server(server)

//クライアント接続ができたときに、connectionイベントが発生
io.on('connection', socket => {
    //クライアント側のentryNotifyイベントをトリガーさせ、挨拶する
    socket.emit('entryNotify', 'welcome!')
    //ルームroomAに参加
    socket.join('roomA')

    //registerUserイベントリスナー
    socket.on('registerUser', username => {
        //登録者以外のクライアント接続を通知、クライアント側のnewUserNotifyイベントをトリガー
        socket.broadcast.emit('newUserNotify', `BroadCast: new user ${username} has registered`)
    })

    // chatイベントリスナー
    socket.on('chat', ({msg, room}) => {
        //同じRoomにいるクラインと接続に投稿を通知、クライアント側のroomNotifyイベントをトリガー
        io.to(room).emit("roomNotify", msg) 
    })

})

```

■動作結果(デバッグコンソールにて確認可能)
イベント通知はいつも通りの非同期の処理

```
2 welcome!
socket1 receives BroadCast: new user Piyo has registered
socket2 recieves BroadCast: new user Hoge has registered
welcome!
socket3 receives BroadCast: new user Hoge has registered
socket3 receives BroadCast: new user Piyo has registered
socket1 receives BroadCast: new user Foo has registered
socket1 receives Can you hear me?? 
socket1 receives Can you hear me?? 2x 
socket1 receives Can you hear me?? 3x 
socket1 receives Stop spamming!
socket2 recieves BroadCast: new user Foo has registered
socket2 receives Can you hear me?? 
socket2 receives Can you hear me?? 2x 
socket2 receives Can you hear me?? 3x 
socket2 receives Stop spamming!
socket3 receives Can you hear me?? 
socket3 receives Can you hear me?? 2x 
socket3 receives Can you hear me?? 3x 
socket3 receives Stop spamming!
socket3 receives I can hear you!
socket1 receives I can hear you!
socket2 receives I can hear you!

```