javascript 来自 Android 和 IOS 客户端的棘轮套接字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31566556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ratchet socket from Android and IOS clients
提问by Misha Akopov
I've written socket PHP code using Ratchet. Here is simple code, that works when I send and get messages from web - javascript:
我已经使用Ratchet编写了套接字 PHP 代码 。这是简单的代码,当我从网络发送和接收消息时有效 - 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);
}
}
}
}
The problem is when I use java client - from Android App. I use thread from Activity. It has no exceptions, no errors. client.isConnected() is true. But no server code is not called - onOpen method, onMessage and others. How Can I fix this. Almost the same situation is with IOS. Client Connects to server but nither of those Ratchet methods are called. They are called only from javascript. Java code :
问题是当我使用 java 客户端 - 从 Android 应用程序。我使用来自 Activity 的线程。它没有例外,没有错误。client.isConnected() 为真。但是没有不调用任何服务器代码 - onOpen 方法、onMessage 和其他方法。我怎样才能解决这个问题。IOS 的情况几乎相同。客户端连接到服务器,但没有调用这些 Ratchet 方法。它们仅从 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();
采纳答案by Iraklii
Try to use for
Android: https://github.com/TooTallNate/Java-WebSocket
iOS: https://github.com/square/SocketRocket
Because Ratchet is WebSocket. And your host name should starts from ws://
尝试用于
Android:https: //github.com/TooTallNate/Java-WebSocket
iOS:https: //github.com/square/SocketRocket
因为 Ratchet 是 WebSocket。你的主机名应该从 ws:// 开始