
実現したいこと
Socket.ioをExpressで作ったプロジェクトに組み込みたい
前提
Express Generatorで作ったプロジェクトのルーターからsocketを使いたい。
マッチング式の1対1の対戦ゲームが作りたいです。あるルーム名を入力するとそこにルームができて、二人がそのルームに入ったらそれ以上は入れないようにし、そのルームの名前の共有で友達と遊べるようにしたいです。
プロジェクトの構造
│ app.js │ ├─bin │ www │ ├─public │ ├─images │ ├─javascripts │ │ singleplayer.js │ │ │ └─stylesheets │ game.css │ style.css │ ├─routes │ index.js │ matching.js │ singleplayer.js │ users.js │ └─views error.ejs index.ejs matching.ejs singleplayer.ejs
ソースコード
matching.js
js
1const express = require('express'); 2const router = express.Router(); 3const app = express(); 4const server = require('http').createServer(app); 5const io = require('socket.io')(server | {serveClient: true}); 6let room = 'aaa' 7 8io.on('connection', (socket) => { 9 console.log('User connected'); 10 11 // Add the user to the room 12 socket.join(room); 13 14 // Notify the user that they have joined the room 15 socket.emit('joined', room); 16}); 17 18router.post('/',(req,res,next) => { 19 console.log("matching..."); 20 room = req.body['room_id']; 21 let data = { 22 title: 'Title', 23 content: room 24 }; 25 res.render('matching',data); 26}); 27 28module.exports = router;
matching.ejs
ejs
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <title><%= title %></title> 5 <link rel='stylesheet' href='/stylesheets/style.css' /> 6 <script src="/socket.io/socket.io.js"></script> 7 <script> 8 const socket = io(); 9 const room = 'aaa'; 10 // When the player joins the room 11 socket.on('joined', (room) => { 12 console.log('Joined room:', room); 13 }); 14 </script> 15</head> 16<body> 17<h1>matching</h1> 18<p><%- content %></p> 19</body> 20</html>
発生している問題・エラーメッセージ
エラーメッセージ↓
GET /socket.io/?EIO=4&transport=polling&t=OSp6vHi 404 0.891 ms - 1333
接続できないです;(
教えてほしいこと
どうやったらpostを受け取ったときにsocketを開くか、そもそもそれであっているのか
どうやったら新しいルームみたいな感じのものができるか
初歩的ですが回答お願いします。

