我使用 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);
}
}
}
}
问题是当我使用来自 Android 应用程序的 java 客户端时。我使用 Activity 中的线程。它没有异常(exception),没有错误。 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();
最佳答案
尝试用于
安卓:https://github.com/TooTallNate/Java-WebSocket
iOS:https://github.com/square/SocketRocket
因为 Ratchet 是 WebSocket。你的主机名应该从 ws://开始
关于javascript - 来自 Android 和 IOS 客户端的 Ratchet 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31566556/