php - 从 PHP 网站 node.js 多人游戏连接。如何跟踪用户?
问题描述
我目前有一个 php 网站正在运行。在这里,我可以保留和使用任何会话数据来跟踪我的用户。但是,如果我只是使用简单的超链接从该网站连接到我的 node.js 游戏,例如...
<a href="http://localhost:8080">
这可行,我确实连接到在该端口上的本地主机上运行的游戏,这里是用于设置 node.js 游戏的代码。
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const TDSGame = require('./../tds-game');
const { log } = require('console');
const app = express();
// path for our client files
const clientPath = `${__dirname}/../client`;
console.log(`Serving static from ${clientPath}`);
// for static middleware from express
app.use(express.static(clientPath));
const server = http.createServer(app);
const io = socketio(server);
var waitingPlayers = [];
io.on('connection', (sock) => {
if(waitingPlayers.length == 3){
waitingPlayers.push(sock);
new TDSGame(waitingPlayers);
waitingPlayers = [];
}
else{
waitingPlayers.push(sock);
sock.emit('message', 'Waiting for opponent');
}
sock.on('message', (text)=>{
// io.emmit everyone connected to the server receives the message
io.emit('message', text);
});
});
server.on('error', (err)=>{
console.log('Server Error', err);
});
server.listen(8080, ()=>{
console.log('TDS started on 8080');
});
什么是传递我不知道哈希和用户名或其他东西的玩家的好方法。到游戏等连接我可以获得这些变量并检查我的玩家是否存在于数据库中?如果是这样,那么将这些玩家和套接字传递给游戏逻辑?我正在努力任何帮助将不胜感激谢谢:)
解决方案
您可以向套接字连接 URL "http://localhost:8080?foo=bar&hi=hello" 添加额外的参数,通过它,您可以在 socket-clint 连接时获取数据(io.on('connection')事件)。
并且您可以在断开连接时从数组( waitingPlayers )中删除数据。通过这种方式,您可以管理连接。
我确实将 socket.io 用于我的聊天应用程序,其中我使用 redis 而不是 Array 来存储连接 ID 以发送和接收消息。
推荐阅读
- linux - 删除目录(如果存在)
- python - 如何在 PyCharm 中指定用于从 requirements.txt 安装的 pip 选项
- angular - 在 Angular 表中显示每个父母的孩子总数
- assembly - BITswap 组装程序
- php - 不同浏览器的 Laravel Redis 行为
- weblogic - 如何在 Weblogic wlst Offline 中设置多个 JNDI 名称
- c - 有人能解释一下为什么我第一次打印 0,但在 *p = 6.35 之后,它可以打印 6.35?
- swift - AdMob 未显示在复制的 Swift 项目中
- c# - 从静态 void 中的接口或抽象类调用方法
- c# - 如何将 JSON 结果链接到 Syncfusion Scheduler xamarin