我正在开发一个 Web 应用程序,我需要以下场景的实时行为,
应用程序将有两种类型的用户Player
和Spectator
. 玩家可以加入正在进行的游戏,而观众可以只是旁观。
游戏将由管理员用户初始化。
观众基本上是可以看到加入游戏的人员列表的人。当然,这需要是实时的,当玩家断开连接或新玩家加入游戏时,观众看到实时列表。
总结一下,考虑下面的例子
Spectator_1 joins Clan_101
Spectator_2 joins Clan_201
Player_1 joins Clan_101 // Need to broadcast this event to Spectator_1
Player_2 joins Clan_101 // Need to broadcast this event to Spectator_1
Player_1 disconnects Clan_101 // // Need to broadcast this event to Spectator_1
Player_11 joins Clan_201 // Need to broadcast this event to Spectator_2
Player_12 joins Clan_201 // // Need to broadcast this event to Spectator_2
将正在进行的游戏视为主题/频道 ( Ratchet\Wamp\Topic
),我需要向观众广播以下事件player join
以及player left
观众订阅的游戏/主题。
我在服务器端使用Ratchet WebSockets for PHP ,在客户端使用高速公路 js
下面是代码。到目前为止,当玩家加入/断开游戏时,我可以向服务器(从客户端)发送信息。但是当玩家加入或断开连接时,我如何将这些信息广播给观众(客户端)。
播放器.html
<script src="scripts/autobahn.js" type="text/javascript"></script>
<script src="scripts/jquery-1.11.2.min.js" type="text/javascript"></script>
<script>
ab.connect(
'ws://localhost:8080',
function (session) {
appSession = session;
$('#btnJoinGame').on('click',function(){
session.publish('joingame', ['data','GAME_ID']);
});
});
</script>
观众.html
<script>
var conn = new ab.Session(
'ws://localhost:8080',
function() {
conn.subscribe('spectator_GAME_ID', function(topic, data) {
console.log(topic);
console.log(data);
});
},
function() {
console.warn('WebSocket connection closed');
}
);
/* OR Using the legacy syntax */
/*
ab.connect(
'ws://localhost:8080',
function (session) {
session.subscribe("t1011", function (topic, event) {
console.log(event);
});
}
);
*/
</script>
服务器.php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Wamp\WampServerInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface as Conn;
class EventHandler implements WampServerInterface, MessageComponentInterface{
public function __construct(React\EventLoop\StreamSelectLoop $loop){
$this->loop = $loop;
}
public function onSubscribe(Conn $conn, $subscription, $params = array()){
$subscription->broadcast($this->data);
}
public function onPublish(Conn $conn, $topic, $params, array $exclude, array $eligible) {
if($topic->getId() === 'joingame'){
if(!isset($this->data[$params[1]])){
$this->data[$params[1]] = array($params[0]);
}else{
array_push($this->data[$params[1]], $params[0]);
}
}
/** DOES'NT WORKS **/
$newtopic = new Ratchet\Wamp\Topic('spectator_GAME_ID');
$this->onSubscribe($conn,$newtopic);
}
/*Omitting other methods for brevity*/
}
$loop = React\EventLoop\Factory::create();
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
new Ratchet\Wamp\WampServer(
new EventHandler($loop) // This is my class. Pass in the loop!
)
)
),
$webSock
);
$loop->run();