编程语言
首页 > 编程语言> > javascript-来自Android和IOS客户端的棘轮套接字

javascript-来自Android和IOS客户端的棘轮套接字

作者:互联网

我已经使用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 one rror(\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 App.我使用Activity中的线程.它没有例外,没有错误. client.isConnected()为true.但是没有服务器代码没有被调用-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();

解决方法:

尝试用于
安卓:https://github.com/TooTallNate/Java-WebSocket
的iOS:https://github.com/square/SocketRocket
因为棘轮是WebSocket.并且您的主机名应以ws://开头

标签:ratchet,sockets,ios,javascript,android
来源: https://codeday.me/bug/20191120/2040358.html