Как отправлять и получать данные с сервера с помощью Ratchet

Это первый раз, когда я использую сокеты и начал с трещотка но я серьезно не могу вписаться в это. Все еще пытался объединить некоторые части из учебника, но столкнулся с некоторыми проблемами. Плюс я хотел бы знать, как использовать autobahn.js с этим. Уроки не понятны.

Моя проблема

1) Как отправить сообщение всем пользователям, кроме текущего, с указанием «… присоединился» и «…» должен быть IP-адресом пользователя.

Я попробовал следующее, но это дает мне ошибку на терминале.

public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
$this->send('new');
echo "New connection! ({$conn->remoteAddress})\n";
}

Вызов неопределенного метода MyApp \ Chat :: send ()

2) Что нужно сделать, чтобы при отправке сообщения все стороны могли просмотреть его, включая того, кто его отправляет (так работает каждый чат)?

JS

var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function(e) {
//console.log("Connection established!");
$("#chat_window #messages_list").append("<li class='join_disconnect'>127.0.0.1 Online</li>");
}
conn.onmessage = function(e) {
//console.log(e.data);
$("#chat_window #messages_list").append("<li class='thread'>"+e.data+"</li>");
}
conn.onclose = function(e) {
//console.log("Connection Disconnected!");
$("#chat_window #messages_list").append("<li class='join_disconnect'>127.0.0.1 Offline</li>");
};$(document).ready(function(){

disable_button();//EMERGENCY EXIT
$('#exit').click(function(){
window.location.replace('http://www.google.com');
});//PREVENT BLANK INPUT
$('#msg').on('keyup', function(e){

if($(this).val().length>0){
enable_button();
}
else{
disable_button();
}

});

//SEND MESSAGE
$('#snd').click(function(){
var thread = $('#msg').val();
//console.log(thread);
//conn.send(thread);
$.ajax({
type:'POST',
url: './bin/send-message.php',
data: {msg: thread},
success: function(response){
//alert(response);
if(response!=1){
$('#msg').val('');
disable_button();
}
}
});
});

//ENABLE BUTTON
function enable_button() {
var element = document.getElementById('snd');
$(element).addClass('active');
element.style.pointerEvents = '';
}

//DISABLE BUTTON
function disable_button() {
var element = document.getElementById('snd');
$(element).removeClass('active');
element.style.pointerEvents = 'none';
}});

Я знаю, что это много вопросов, но я действительно хочу знать, как. Если есть какие-то пошаговые инструкции по обучению, они также приветствуются.

0

Решение

Если вы пытаетесь изменить пример с руководство на Сайт Rachet, чем для вашего первого решения проблемы является:

public function onOpen(ConnectionInterface $conn) {
// first, you are sending to all existing users message of 'new'
foreach ($this->clients as $client) {
$client->send('new');
}
// than,
// Store the new connection to send messages to later
$this->clients->attach($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 $client) {
// remove this check
// if ($from !== $client) {
// The sender is not the receiver, send to each client connected
// $client->send($msg);
// }

// just send to all
$client->send($msg);
}
}

Обновить: полное решение.

в Chat.phpВам необходимо изменить некоторые методы:

public function onOpen(ConnectionInterface $conn) {
// first, you are sending to all existing users message of 'new'
foreach ($this->clients as $client) {
$client->send('<status>' . $conn->remoteAddress . ' Online</status>'); //here we are sending a status-message
}
// than,
// Store the new connection to send messages to later
$this->clients->attach($conn);

echo "New connection! ({$conn->remoteAddress})\n";
}

public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);

//send to others clients message about disconnected user
foreach ($this->clients as $client) {
$client->send('<status>' . $conn->remoteAddress . ' Offline</status>'); //here we are sending a status-message too
}

echo "Connection {$conn->remoteAddress} has disconnected\n";
}

в вашем js код, измените следующий метод:

conn.onmessage = function(e) {
//console.log(e.data);
var match = e.data.match(/^<status>(.*?)<\/status>$/i);
if (match) {
if (/\d+\.\d+\.\d+\.\d+ online/i.test(match[1])) {
messages.append('<li class="join_connect">' + match[1] + "</li>");
} else if (/\d+\.\d+\.\d+\.\d+ offline/i.test(match[1])) {
messages.append('<li class="join_disconnect">' + match[1] + "</li>");
}
} else {
messages.append('<li class="thread">' + e.data + "</li>");
}
};
2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector