[英]Server creates room socket.io and specific url
我想通過服務器創建動態房間並像這樣個性化 URL:localhost:3000/path/path.php?roomId。
我有一個表格供用戶輸入他們的姓名,然后他們單擊提交按鈕“創建房間”,他們將進入一個帶有此類 url 的頁面:“ localhost:3000/path/path.php?roomId ”其中roomId單擊按鈕時由服務器創建。
在我創建房間的那一刻,我只有 URL“ localhost:3000/path/path.php ”,但我想個性化 URL,使其變為localhost:3000/path/path.php?roomId
其背后的想法是能夠將鏈接localhost:3000/path/path.php?roomId共享給其他用戶,以便他們只需單擊共享鏈接即可直接加入房間(代碼用於多人游戲,所以我想為游戲 skribbl.io 創建一個可共享的 url 和唯一鏈接)。
然而; 我只看到用戶輸入房間名稱的教程,所以我不知道如何解決這個問題。
這是我的代碼: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);
});
}
客戶端.js:
const socket = io(document.location.protocol+'//'+document.location.host +":3000");
socket.emit('createRoom');
表單 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/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)從客戶端移動到服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.