I've written socket PHP code using Ratchet . Here is simple code, that works when I send and get messages from 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);
}
}
}
}
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 :
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();
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://