Before asking this question, I did my best by reading severel
questions on SO (tagged Ratchet and dealing with similar issues but to
no avail. I even asked a question which received no attention and I
therefore deleted it to write another one (that hopefully is more
clear).
我的最终目标是使用Ratchet构建一对一的私人聊天应用程序.除了我无法向特定用户发送消息外,一切正常.
每个登录用户在访问网站的安全区域时连接到websocket服务器:
$(document).ready(function() {
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
// Here I need to send the logged in user_id to websocket server
// and get it in onOpen method so that I can index my array
// of connections with user_id instead of
//$connection->ResourceId, I explain more below
};
conn.onmessage = function(e) {
console.log(e.data);
};
});
当用户在聊天框中写入消息时,消息将通过AJAX发送到Web服务器,然后使用ZeroMQ推送到Websocket.在控制器中:
// Persistence of Message(message_id, sender_id, receiver_id, message_text)
.....
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$pushData = array(
'receiver_id' => $receiver_id,
'sender_id' => $user->getId(),
'message' => $message->getMessageText(),
);
$socket->send(json_encode($pushData));
所以最后,我的websocket服务器能够知道哪个是使用JSON的接收者的id.但他怎么知道该用户的连接是什么?换句话说,我需要将websocket连接存储在由用户id索引的数组中.
namespace RealTime;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;
class Pusher implements WampServerInterface, MessageComponentInterface{
private $clients;
public function onOpen(ConnectionInterface $conn) {
$this->clients[$conn->resourceId] = $conn;
// I need here to get the user_id received from browser while opening connection
}
public function onMessageEntry($entry) {
$entryData = json_decode($entry, true);
//This is not what I need (It sends to all users in array)
foreach ($this->clients as $key => $client) {
$client->send($entryData['message']);
}
}
public function onMessage(ConnectionInterface $from, $msg) {
echo $msg;
}
}
和websocket服务器:
require dirname(__DIR__) . '/vendor/autoload.php';
use RealTime\Pusher;
$loop = React\EventLoop\Factory::create();
$pusher = new Pusher;
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555');
$pull->on('message', array($pusher, 'onMessageEntry'));
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0');
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
new Ratchet\Wamp\WampServer(
$pusher
)
)
),
$webSock
);
$loop->run();
?>
问题:
>如何在打开connection时从客户端发送登录的user_id.我需要在websocket服务器中获取值,以便我可以用它来索引我的客户端数组($client [user_id] = $conn而不是$client [recourceId ] = $康恩).我尝试了javascript函数发送,但我不知道从哪里接收发送的数据(即使onMessage没有打印任何东西).
>为什么onMessage方法甚至没有执行MessageComponentInterface实现(是因为我有onMessageEntry方法$pull-> on(‘message’,array($pusher,’onMessageEntry’));代码行?
谢谢.