棘轮WebSocket服务器可以向客户端发送消息吗?
我想使用棘轮(http://socketo.me)在iPhone应用程序和服务器之间进行永久连接。我需要在应用程序和服务器之间交换数据。棘轮WebSocket服务器可以向客户端发送消息吗?
从这个例子(http://socketo.me/docs/hello-world),我发现我有一个函数的onMessage当应用程序发送按摩到服务器将被调用,服务器可以发送到应用程序的响应。
但是服务器还必须有能力发送数据到应用程序,而无需从应用程序获取数据。例如,应用程序和服务器之间的连接已经建立。服务器发生某些事情,我们需要向应用发送新数据。我该怎么做,这有可能吗?
主要问题是如何从服务器发送数据到应用程序?
谢谢你的帮助。
这确实是可能的。您需要以某种方式与WebSocket服务器进程通信。您可以通过使用某种形式的消息传递来完成此操作,无论是RPC还是消息队列。
棘轮本身基于React事件循环。这意味着与Ratchet的任何形式的通信都必须与该事件循环集成。 On the React homepage你可以看到一些已经存在的集成的:
- Predis/Async(你可以使用消息传递的Redis的pub/sub)
- DNode-PHP(dnode是一个基于TCP的RPC协议)
- React/ZMQ(积分事件循环与ZeroMQ)
- React/Stomp(实施STOMP协议的,允许你交谈的消息如RabbitMQ)
- JCook21/ReactAMQP(用于阵营PHP AMQP绑定)
在棘轮文档有a tutorial on how to use React/ZMQ,以推动从任何地方邮件到您的WebSocket服务器。
棘轮还实施WAMP,其中包括PubSub。因此,您的客户可以订阅一些主题,并且可以让其他客户端(即在您的后端基础结构上运行)发布到这些主题。您可以将基于AutobahnPython的客户端通过Ratchet发布到基于AutobahnAndroid的移动应用程序或基于AutobahnJS的HTML5客户端。
它使用wampv1,iOS没有v1的库。 有没有办法使用MessageComponent接口进行推送? –
高速公路支持WAMPv2 https://github.com/voryx/Thruway,所以你应该能够使用它https://github.com/mogui/MDWamp – oberstet
我有完全相同的问题,这就是我所做的。
基于hello world tutorial,我用一个数组替换了SplObjectStorage。在介绍我的修改之前,我想评论一下,如果你通过该教程并理解它,唯一阻止你自己到达此解决方案的事情可能不知道SplObjectStorage是什么。
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = array();
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients[$conn->resourceId] = $conn;
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $key => $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
// Send a message to a known resourceId (in this example the sender)
$client = $this->clients[$from->resourceId];
$client->send("Message successfully sent to $numRecv users.");
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
unset($this->clients[$conn->resourceId]);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
当然,为了使它非常有用,您可能还想添加数据库连接,并存储/检索这些resourceIds。
谢谢你的帮助。 – lexa
React/ZMQ的好例子。但是我找不到如何将正确的数据(例如,我创建的特殊JSON)推送给适当的用户。例如,我必须将数据发送给适当的用户(我有用户标识的列表)。这是必要的,用户已经订阅了'特定页面'(就像他们在这里说的:http://socketo.me/docs/push)? – lexa
igorw,我们要以某种方式连接云(skype,例如)直接向您提出问题。并感谢您的帮助。 – lexa