gpt4 book ai didi

websocket - Ratchet WAMP onpublish 总是发布到所有客户端,包括发布调用者与否?

转载 作者:行者123 更新时间:2023-12-04 16:13:39 26 4
gpt4 key购买 nike

我刚刚为 Ratchet WAMP + autobahn 版本 1 制作了一个聊天 hello world。
full source code here if you want to see

JavaScript 客户端发送聊天消息:

           function click_send_btn() {
var json_data = {
"message": $.trim($("#input_message").val())
};
sess.publish("send_message", json_data, true);
}


PHP Ratchet 服务器发布消息:

public function onPublish(\Ratchet\ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
switch ($topic) {
case 'http://localhost/enter_room':
$foundChater = $this->allChater[$conn];
$newChaterName = $event['username'];
$foundChater->setChatName($newChaterName);
break;
case 'send_message':
$foundChater = $this->allChater[$conn];
$event['username']=$foundChater->getChatName();
break;
}
$topic->broadcast($event);
echo "onPublish {$conn->resourceId}\n";
}


enter image description here

我不明白为什么用 excludeme 发布不起作用。
在上面2个firefox中,对firefox说:我是吧。该消息不应该显示在他自己身上,但确实如此。

doc ref: autobahn version 1 javascript publish with excludeme

doc ref: ratchet onpublish

doc ref: ratchet topic broadcast

最佳答案

我刚刚修好了。
我真是个傻瓜。我没有处理参数“array $exclude”
我还使用 $topic->broadcast($event) 强制向所有人广播。
现在我创建一个函数

/**
* check whitelist and blacklist
*
* @param array of sessionId $exclude -- blacklist
* @param array of sessionId $eligible -- whitelist
* @return array of \Ratchet\ConnectionInterface
*/

private function getPublishFinalList(array $exclude, array $eligible) {
//array of sessionId
$allSessionId = array();
$this->allChater->rewind();
while ($this->allChater->valid()) {
array_push($allSessionId, $this->allChater->current()->WAMP->sessionId);
$this->allChater->next();
}

//if whitelist exist, use whitelist to filter
if (count($eligible) > 0) {
$allSessionId = array_intersect($allSessionId, $eligible);
}

//then if blacklist exist, use blacklist to filter
if (count($exclude) > 0) {
$allSessionId = array_diff($allSessionId, $exclude);
}

//return array of connection
$result = array();
$this->allChater->rewind();
while ($this->allChater->valid()) {
$currentConn = $this->allChater->current();
if (in_array($currentConn->WAMP->sessionId, $allSessionId)) {
array_push($result, $currentConn);
}
$this->allChater->next();
}
return $result;
}

在 onPublish 中,我不再使用 $topic->broadcast($event) 了。

    $conn2PublishArray = $this->getPublishFinalList($exclude, $eligible);
foreach ($conn2PublishArray as $conn2Publish) {
$conn2Publish->event($topic, $new_event);
}


连接类有一个方法“even”,它可以直接向“订阅者”发送消息。
Ratchet.Wamp.WampConnection event method

关于websocket - Ratchet WAMP onpublish 总是发布到所有客户端,包括发布调用者与否?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25155258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com