简体   繁体   English

如何使用Ratchet从服务器发送和获取数据

[英]How to send and get data from the server using Ratchet

This is the first time I am using sockets and started off with Ratchet but I seriously cant fit my head into it. 这是我第一次使用套接字,并从Ratchet开始使用,但是我严重无法适应它。 Still tried to join together some parts from the tutorial but facing some problems. 仍然尝试将本教程中的某些部分结合在一起,但遇到了一些问题。 Plus I would like to know how to use autobahn.js with it. 另外,我想知道如何与它一起使用autobahn.js The tutorials are not clear. 这些教程不清楚。

My Problem 我的问题

1) How to send a message to all users except the current user stating " ... joined" and the '...' has to be the ip of the user. 1)如何向所有用户发送消息,当前用户除外,说明“ ...已加入”,而“ ...”必须是该用户的ip。

I tried the following but it gives me error on the terminal. 我尝试了以下操作,但它在终端上给了我错误。

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";    
}

Call to undefined method MyApp\\Chat::send() 调用未定义的方法MyApp \\ Chat :: send()

2) What to do so that when a message is sent all the parties can view it including the one who is sending it (that's the way how every chat works)? 2)怎么做,以便在发送消息时,所有各方(包括正在发送消息的人)都可以查看该消息(这就是每次聊天的工作方式)?

JS 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';
        }


});

I know these are a lot of questions but I really want to know how. 我知道这些问题很多,但我真的很想知道。 If there are any step by step easy to learn tutorials those are also welcome. 如果有任何循序渐进的易学教程,也欢迎您。

If you are trying to change example from the tutorial at the Rachet site , than for your first problem solution is: 如果您尝试从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";
}

Regarding your second question, if I get you right, you should send new messages to all connected clients, like this: 关于第二个问题,如果我说对了,您应该向所有连接的客户端发送新消息,如下所示:

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);
    }
}

Update : complete solution. 更新 :完整的解决方案。

In the Chat.php , you need to modify some methods: 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";
}

in your js code, modify next method: 在您的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>");
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用棘轮式Websocket将数据发送到服务器上? - How do you send data to the server onload using ratchet websockets? Ratchet + Symfony3:如何从外部访问当前服务器 - Ratchet + Symfony3: how to get access to current server from outside 使用 Ratchet Websocket 和 Symfony 获取会话数据 - Get session data using Ratchet Websocket and Symfony Ratchet - 如何防止其他网站连接到我的 websocket 服务器? - Ratchet - How to prevent other websites from connect to my websocket server? 如何使用 ReactPHP 和 Ratchet 在同一端口上运行 WebSocket 和 HTTP Server? - How to run WebSocket and HTTP Server on the same port using ReactPHP and Ratchet? 如何使用android中的HttpUrlConection发送请求以从服务器获取特定数据? - How do I send a request to get specific data from server using HttpUrlConection in android? 如何远程或在服务器上运行Ratchet? - How to run Ratchet remotely or on a server? 如何从GPS获取数据并发送到服务器以及如何保存到数据库 - How to get data from GPS and send to server and how save to database 从棘轮网络套接字向客户端发送消息 - send messege to client from ratchet web socket 如何使用URL将数据从iPhone发送到服务器 - How to send data from iphone to server using the url
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM