Node JS Express JS 客户端/服务器游戏
我正在用 Node.js 和 Express js 编写一个两人纸牌游戏(为简单起见,称其为常规扑克)。有几件事我遇到了麻烦。首先,我如何确保只有 2 名玩家可以访问游戏实例,如果他们失去连接是否可以让他们重新连接?二、如何从服务器向客户端发送消息?我可以在“socket.on”监听器调用中发送它,但在程序的正常范围内我无法让它工作。
var socket = io.listen(app);
socket.on('connection', function(client){
player++;
if(player <= 2) {
var messageout = "player " + player + " connected";
client.broadcast(messageout);
client.on('message', function(data){console.log(data); })
client.on('disconnect', function(){console.log('disconnected');})
}
else {
socket.end;
}
});
我在概念上遇到了这里发生的事情以及如何解决该问题的问题。例如,我是否使用套接字来完成这一切?或者我是否每回合都返回一个包含游戏更新状态(纸牌、投注等)的网页?
I'm writing a two player card game, (say it's regular poker for simplicity) in Node.js and Express js. There's a couple of things I'm having trouble with. First, how do I make sure that there are only 2 players that can access an instance of the game, and is it possible to have them reconnect if they lose the connection? Second, how do send a message from the server to the client? I can send it within the "socket.on" listener call, but within the normal scope of the program I can't get it to work.
var socket = io.listen(app);
socket.on('connection', function(client){
player++;
if(player <= 2) {
var messageout = "player " + player + " connected";
client.broadcast(messageout);
client.on('message', function(data){console.log(data); })
client.on('disconnect', function(){console.log('disconnected');})
}
else {
socket.end;
}
});
I'm having trouble conceptually what's going on here and how to approach the problem. For example, do I do it all with sockets? Or do I return a web page with the updated state of the game (cards, bets, etc.) every turn?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建实例对象数组。
当新玩家加入时,要么创建一个新实例并将其设置为玩家 1,要么将它们添加到现有实例作为玩家 2。
如果您在每个玩家最初连接时向他们发送一个 UUID,您可以让他们在重新连接时使用它进行身份验证。
client.send({ gameState: gameState() });
如果您已将客户端保存到对象中:
instances[ 'game1' ].player1.send( data );
我将处理与网络套接字的所有动态交互。
我不会通过网络套接字发送 html。相反,发送 json 并使用客户端模板来渲染它。
Create an array of instance objects.
When a new player joins either create a new instance and set them as player1, or add them to an existing instance as player two.
If you send each player a UUID when they initially connect you can have them use it to authenticate when they reconnect.
client.send({ gameState: gameState() });
of if you've saved the client into an object:
instances[ 'game1' ].player1.send( data );
I would deal with all dynamic interactions with web sockets.
I wouldn't send html over web sockets. Instead send json and use a client side template to render it.
立即尝试
。Try
now
.