Понимание Ratchet Push WebSockets на стороне клиента
Поэтому я следил за документацией Push на веб-сайте Ratchet здесь: http://socketo.me/docs/push
И пока все хорошо, я могу отправлять туда и обратно сообщения, используя следующее:
чат-server.php
<?php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;
$loop = React\EventLoop\Factory::create();
$pusher = new ChatController;
// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'deliverMsg'));
// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
new Ratchet\Wamp\WampServer(
$pusher
)
)
),
$webSock
);
$loop->run();
ChatController
class ChatController implements WampServerInterface
{
protected $clients;
// public $userID;
protected $subscribedTopics = array();
public function onOpen(ConnectionInterface $conn) { echo "Connection Made \n"; }
public function deliverMsg($event) {
$json = json_decode($event);
$roomID = $json->roomID;
if (!array_key_exists($roomID, $this->subscribedTopics)) {
echo "Message Failed: Not subscribed to $roomID? \n";
return;
}
$topic = $this->subscribedTopics[$roomID];
$topic->broadcast($event);
echo "Message Sent.";
}
public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
$topic->broadcast($event);
echo "published (Not sure when this gets called or what it does?) \n";
}
public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
$conn->callError($id, $topic, 'RPC not supported on this demo');
}
public function onSubscribe(ConnectionInterface $conn, $topic) {
echo "Subscribed to " . $topic . "\n";
$this->subscribedTopics[$topic->getId()] = $topic;
}
public function onUnSubscribe(ConnectionInterface $conn, $topic) { echo "unsubscribed"; }
public function onClose(ConnectionInterface $conn) {}
public function onError(ConnectionInterface $conn, \Exception $e) {}
public function sendMessage(Request $request) {
// removed all queries ect... getting the parameters
$json = ['messageID' => $messageID, 'roomID' => $roomID, 'userID' => $userID, 'message' => $message];
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, '??');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($json, true));
return \Response::json($json);
}
}
chat.blade.php (js)
<script>
@foreach(CoreHelper::openChatRooms() as $openChat)
channelConnect('{{ $openChat->chat_key }}');
@endforeach
function channelConnect(channelName) {
var conn = new ab.Session('ws://localhost:8080',
function() {
conn.subscribe(channelName, function(channel, e) {
addMessage(channel, e);
});
},
function() {
console.warn('WebSocket connection closed');
},
{'skipSubprotocolCheck': true}
);
}
function addMessage(channel, e) {
console.log("new message in channel: " + channel + " \n");
var data = JSON.parse(e);
var messageID = data.messageID;
var roomID = data.roomID;
var userID = data.userID;
var message = data.message;
console.log(message);
}
$(document).on('click', '#sendMessage' , function(e) {
e.preventDefault();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var roomID = $(this).attr('room');
var message = $('#message' + roomID).val();
$.ajax({
url: '/chat/sendmessage',
type: 'POST',
data: {_token: CSRF_TOKEN, roomID: roomID, message: message},
success: function (data) {
}
});
});
</script>
#sendMessage
Пост ajax соединяется с ChatController sendMessage
функция.
Все вышеперечисленные сообщения работают через консоль браузера, и все работает правильно на работающем сервере:
Хотя все это работает, я все еще не совсем уверен, как это работает, чтобы продвинуться дальше в этом, мои вопросы будут:
В chat-server.php у меня есть
$pull->on('message', массив ($pusher, 'deliveryMsg'));
Где это вызывается / активируется? Из того, что я вижу в JavaScript, сообщение как-то отправляется и подключается к
deliverMsg()
функция наconn.subscribe
но как-то только один раз я нажимаю#sendMessage
...conn.subscribe(channelName, function(channel, e) { addMessage(channel, e); });
И серверная сторона после того, как я нажму
#sendMessage
Кнопка последней строки, которая работает в ChatController'ssendMessage()
функция$socket->send(json_encode($json, true));
Так же
$socket->send();
специально активировать / позвонить$pull->on('message', array());
? Если так, где я могу найти другой$socket
функции, которые могут активировать другие функции, хотя$pull->on()
за отписку, закрытие, публикацию и т. д...Как мне отписаться от определенного канала / темы через JS? когда я пытаюсь
conn.unsubscribe(channelName)
консоль возвращает нет такой функции как отписаться