服务器创建房间套接字.IO和特定url



我想通过服务器创建动态房间,并像这样个性化URL: localhost:3000/path/path.php?

我有一个表单供用户输入他们的名字,然后他们点击提交按钮"创建一个房间"他们会进入这样一个页面:">localhost: 3000/道路/path.php吗?roomId"其中roomId由服务器在单击按钮时创建。

目前,当我创建一个房间时,我只有URL ">localhost: 3000/道路/path.php"但我想个性化的URL,所以它变成localhost:3000/path/path.php?roomId

它背后的想法是能够然后共享链接localhost:3000/path/path.php?roomId给其他用户,这样他们就可以直接加入房间只有通过点击共享链接(代码是一个多人游戏,所以我想创建一个可共享的url和唯一的链接,如游戏skribbl.io)。

然而;我只看到用户输入房间名称的教程,所以我不知道如何解决这个问题。

下面是我的代码:server.js
const express = require('express');
const app = express();
const httpServer = require('http').createServer(app);
const { getRandomString } = require("../utils/utils");
const io = require("socket.io")(httpServer, {
cors: {
optionSuccesStatus: 200,
origin: "http://localhost",
methods: ["GET", "POST"],
credentials: true,
}
});
//tbh I don't really understand all those lines, I just got it by following lots of tutorials
app.set('views', '../../path.php');
app.set('view engine', 'php');
app.use(express.urlencoded({ extended: true }));
io.on('connection', client => {
//Creation private room
client.on('createRoom', () => {
var roomId = getRandomString(7); // use a function to create a random code room
console.log("player joined");
client.join(roomId);
});
}

client.js:

const socket = io(document.location.protocol+'//'+document.location.host +":3000");
socket.emit('createRoom');

form page.php:

<form id = "formulaire_creation_jeu" method='POST' action="path.php">
<div id="pseudo" class='form-group mb-6'>
<label for="username" class='form-label inline-block mb-2 text-gray-700'>Pseudo</label>
<input id="username" type='text' name="username" required minlength="2" maxlength="15" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
class='form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 transition ease-in-out focus:text-gray-700 focus:bg-white focus:border-black focus:outline-none'>
<div id="error_container_pseudo"></div>
</div>    
<div>
<button type="submit" class="inline-block px-6 py-2.5 bg-yellow-400 text-black font-medium text-xs font-serif leading-tight uppercase rounded shadow-md hover:bg-yellow-500 hover:shadow-lg focus:bg-yellow-500 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-yellow-500 active:shadow-lg transition duration-150 ease-in-out">
Create a room
</button>  
</div>
</form>

我的代码,当我提交表单,我只是有一个这样的链接:localhost: 3000/道路/path.php。服务器和客户端是连接的,但我不确定它是否创建了一个房间。提前感谢您的帮助

所以您唯一想要的是roomId在服务器端生成——我看不出有什么能阻止你在客户端发出:

const socket = io(document.location.protocol+'//'+document.location.host +":3000");
socket.emit('createRoom');

然后在服务器端:

io.on('connection', client => {
// Create private room
client.on('createRoom', ({roomId}) => {
console.log("Player wants to create a room");
client.join(getRandomString(7));
});
}
唯一的区别是我移动了getRandomString(7)从客户端到服务器。