我编写了使用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);
}
}
}
}
问题出现在我使用Java客户端-从Android应用程序。我使用Activity中的线程,没有任何异常和错误。client.isConnected()为true。但是没有服务器代码被调用-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();