コメントありがとうございます。
修正前はプログラムを入れる前を指しているので、
修正前というのは、Socket.IOに関する処理を入れる前という意味だったのですね。
一旦、Socket.IOに関する処理は全て元に戻して、まず、Socket.IOの接続(connection)が確立できるところを目指すのが良いと思いました。
サーバー側
app.listen
してしまうと動作しないそうですので、引用したコードを参考にExpressにおけるSocket.IOのサーバー側の初期化をします。
createServer
したものを使うイメージのようです。
js
1 const express = require ( "express" ) ;
2 const { createServer } = require ( "http" ) ;
3 const { Server } = require ( "socket.io" ) ;
4
5 const app = express ( ) ;
6 const httpServer = createServer ( app ) ;
7 const io = new Server ( httpServer , { /* options */ } ) ;
8
9 io . on ( "connection" , ( socket ) => {
10 console . log ( socket . id ) ;
11 } ) ;
12
13 httpServer . listen ( 3000 ) ;
CAUTION
Using app.listen(3000) will not work here, as it creates a new HTTP server.
(app.listen(3000)
を使用すると、新しい HTTP サーバーが作成されるため、ここでは動作しません。)
https://socket.io/docs/v4/server-initialization/#with-express
クライアント側
クライアント側でSocket.IOの初期化(io()
)をしていますが、クライアント側のSocket.IOのライブラリーは読み込みされていますでしょうか?
していない場合は次の引用を参考にライブラリーを読み込みます。
(Pugのコードに記載がないようでしたので念の為確認させていただきました)
(HTMLの場合)
html
1 < script src = " https://cdn.socket.io/4.4.1/socket.io.min.js " integrity = " sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H " crossorigin = " anonymous " > </ script >
(Pugの場合)
pug
1 script ( src = "https://cdn.socket.io/4.4.1/socket.io.min.js" , integrity = "sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" , crossorigin = "anonymous" )
https://socket.io/docs/v4/client-installation/
それからクライアント側のSocket.IOを初期化します。
js
1 const socket = io ( ) ;
2 socket . on ( "connect" , ( ) => {
3 console . log ( socket . id ) ;
4 } ) ;
https://socket.io/docs/v4/client-initialization/#from-the-same-domain
ここまで実装するとサーバー側とクライアント側の接続が確立されるはずです。
(クライアント側のio()
が実行されて、サーバー側のio.on("connection", () => {})
が動くはずです)
そして、Expressを起動したターミナルにソケットのidが出力されるはずです。
ブラウザーのコンソールにも同じidが出力されるはずです。
joinってクライアント側の変数だったんですね!
すみません、、joinメソッドのことではなく、barr
とwarr
変数がクライアント側で定義されているもので、それをサーバー側で使ってしまっている、という意味で書きました。
joinメソッドはサーバー側のAPIで、ソケットをルームに追加するためのもののようですね。
socket.join(room)
Adds the socket to the given room or to the list of rooms.
(ソケットを指定されたルームまたはルームのリストに追加します。)
https://socket.io/docs/v4/server-api/#socketjoinroom
接続が確立できたら、次はソケットをルームに追加するところですかね。
(まだデータの共有とかは考えない方が良いと思います)
ブラウザーからボタンをクリックした時にルームに追加するのか、
ページを読み込んだ時に(ボタンをクリックする前に)ルームに追加するのか、
混乱してしまっているように見えましたので、
それらを整理した上で少しずつ記述すると良いと思いました。
追記
追記です。
最小限のサンプルアプリを書いてみました。
読んだだけでは理解できないところもあると思いますので、面倒でもご自身で一度動かしてみることが大切かな?と思います。
ショートカットしようとすると後でそのツケを払うことになり、結果的に遠回りになってしまう、というのが個人的な経験則です・・
js
1 // app.js
2 const express = require ( "express" )
3 const { createServer } = require ( "http" )
4 const { Server } = require ( "socket.io" )
5
6 const app = express ( )
7 const httpServer = createServer ( app )
8 const io = new Server ( httpServer , { /* options */ } )
9 const port = 3000
10
11 app . set ( "view engine" , "pug" )
12
13 app . get ( "/" , ( req , res ) => {
14 res . render ( "index" , { title : "Hey" , message : "Hello there!" } )
15 } )
16
17 app . get ( "/window1" , ( req , res ) => {
18 res . render ( "window1" )
19 } )
20
21 const socketPerRoom = 2
22 let socketCount = 0
23
24 io . on ( "connection" , ( socket ) => {
25 console . log ( ` connection socket.id: ${ socket . id } ` )
26 socket . on ( "join" , ( ) => {
27 socketCount ++
28 const room = ` room ${ Math . ceil ( socketCount / socketPerRoom ) } `
29 // ソケットをルームに追加する
30 socket . join ( room )
31 console . log ( ` join socket.id: ${ socket . id } , socket.rooms: ${ JSON . stringify ( [ ... socket . rooms ] ) } ` )
32 // ルーム全体に送信する(最大2つのソケット)
33 io . to ( room ) . emit ( "joined" , socket . id , room )
34 } )
35 } )
36
37 httpServer . listen ( port , ( ) => {
38 console . log ( ` Example app listening on port ${ port } ` )
39 } )
.
pug
1 //- views/index.pug
2 html
3 head
4 title = title
5 body
6 h1 = message
7 input ( type = "button" , value = "join" , id = "button1" )
8 script .
9 window . addEventListener ( "DOMContentLoaded" , ( ) => {
10 const button1 = document . querySelector ( "#button1" )
11 button1 . addEventListener ( "click" , ( ) => {
12 //- 別ウィンドウで開く(Socket.IOの接続は別ウィンドウで)
13 window .open ( "/window1" , "_blank" )
14 })
15 })
.
pug
1 //- views/window1.pug
2 html
3 head
4 title = "Window1"
5 script ( src = "https://cdn.socket.io/4.4.1/socket.io.min.js" , integrity = "sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" , crossorigin = "anonymous" )
6 body
7 h1 = "Window1"
8 ul ( id = "ul1" )
9 script .
10 window . addEventListener ( "DOMContentLoaded" , ( ) => {
11 //- Socket.IO接続
12 const socket = io()
13 socket .on ( "connect" , () => {
14 //- 接続した時のイベント
15 //- ソケットのIDをコンソールと画面のリストに出力する
16 console .log ( `connect: ${socket.id}` )
17 const li1 = document.createElement('li')
18 li1 .textContent = `connect socket.id: ${socket.id}`
19 const ul1 = document.querySelector("#ul1")
20 ul1 .append ( li1 )
21 })
22 socket .on ( "disconnect" , () => {
23 console .log ( `disconnect: ${socket.id}` )
24 })
25 socket .on ( "joined" , ( socketId , room ) => {
26 //- ルームに追加した時のイベント
27 //- ルームに追加されたソケットのIDとルームの名前をコンソールと画面のリストに出力する
28 console .log ( `joined socketId: ${socketId} , room: ${room}` )
29 const li1 = document.createElement('li')
30 li1 .textContent = `joined socketId: ${socketId}, room: ${room}`
31 const ul1 = document.querySelector("#ul1")
32 ul1 .append ( li1 )
33 })
34 //- サーバーに送信する(ルームに追加するためのイベント)
35 socket .emit ( "join" )
36 })
.
json
1 // package.json
2 {
3 "name" : "sample" ,
4 "version" : "1.0.0" ,
5 "description" : "" ,
6 "main" : "app.js" ,
7 "scripts" : {
8 "test" : "echo \"Error: no test specified\" && exit 1"
9 } ,
10 "author" : "" ,
11 "license" : "ISC" ,
12 "dependencies" : {
13 "express" : "^4.17.2" ,
14 "pug" : "^3.0.2" ,
15 "socket.io" : "^4.4.1"
16 }
17 }
実行すると次のようになります。
一人目、二人目はroom1
に追加されます。
(二人目が追加された時に一人目のウィンドウに二人目のソケットIDも出力されます)
三人目はroom2
に追加されます。
sh
1 % node app.js
2 Example app listening on port 3000
3 connection socket.id: BYCS0K4ZwIzA0HnbAAAB
4 join socket.id: BYCS0K4ZwIzA0HnbAAAB, socket.rooms: ["BYCS0K4ZwIzA0HnbAAAB","room1"]
5 connection socket.id: 3qos0oYduumeQfBnAAAD
6 join socket.id: 3qos0oYduumeQfBnAAAD, socket.rooms: ["3qos0oYduumeQfBnAAAD","room1"]
7 connection socket.id: rAIBndZzCigIRUn2AAAF
8 join socket.id: rAIBndZzCigIRUn2AAAF, socket.rooms: ["rAIBndZzCigIRUn2AAAF","room2"]
メインウィンドウ
別ウィンドウ一人目
(二人目が入った後にキャプチャしたため二人目のソケットIDも出力されます。同じルームに追加されたことの確認)
別ウィンドウ二人目
別ウィンドウ三人目
(三人目はルーム2に追加されます)
サーバー側で勝手にルームを割り振って良いのか、クライアント側からルームを指定するのか、設計を検討する必要がありそうかな?と思いました。