棘轮插座从Android和IOS客户端

Ratchet socket from Android and IOS clients

本文关键字:IOS 客户端 Android 插座      更新时间:2023-09-26

我使用Ratchet编写了套接字PHP代码。下面是简单的代码,当我从web - javascript发送和获取消息时有效:

    use Ratchet'MessageComponentInterface;
    class Chat implements MessageComponentInterface{
        protected $clients;
        public function __construct(){
            $this->clients = new SplObjectStorage();
        }
        function onOpen('Ratchet'ConnectionInterface $conn)
        {
            echo "Did Open'n";
            $this->clients->attach($conn);
        }

        function onClose('Ratchet'ConnectionInterface $conn)
        {
            echo "Did Close'n";
            $this->clients->detach($conn);
        }

        function onError('Ratchet'ConnectionInterface $conn, 'Exception $e)
        {
            echo "The following error occured: ". $e->getMessage();
        }

        function onMessage('Ratchet'ConnectionInterface $from, $msg)
        {
            $msgObj = json_decode($msg);
            echo $msgObj->msg;
            foreach($this->clients as $client){
                if($client !== $from){
                    $client->send($msg);
                }
            }
        } 
}

问题是当我使用java客户端-从Android应用程序。我使用线程从活动。它没有异常,没有错误。client.isConnected()为真。但是没有服务器代码不调用- onOpen方法,onMessage等。我怎样才能解决这个问题。IOS也是如此。客户端连接到服务器,但没有调用这两个棘轮方法。它们只能从javascript中调用。Java代码:

new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client = new Socket("XX.XX.XX.XX", 2000);
                    printWriter = new PrintWriter(client.getOutputStream());
                    printWriter.write("Android Message");
                    printWriter.flush();
                    printWriter.close();
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

尝试使用
Android: https://github.com/TooTallNate/Java-WebSocket
iOS: https://github.com/square/SocketRocket
因为棘轮是WebSocket。你的主机名应该以ws://

开头