2016-12-06 11 views
1

私は現在、qtサーバとJavaクライアントの間で少しのネットワーク通信をしようとしています。Qtサーバ/ Javaクライアント通信の問題

私の例では、クライアントはサーバーにイメージを送信します。私の問題は今では、サーバーはデータを見ることがないので、bytesAvailable()は0を返します。

QDataStream、QTextStream、readAll()はすでにデータを試しています。

サーバー:

QTcpServer* tcpServer; 
QTcpSocket* client; 
tcpServer = new QTcpServer(); 

if(!tcpServer->listen(QHostAddress::Any, 7005)){ 
    tcpServer->close(); 
    return; 
} 
... 
tcpServer->waitforNewConnection(); 
client = tcpServer->nextPendingConnection(); 
client->waitForConencted(); 
while(client->state()==connected){ 
    // Syntax here might be iffy, did it from my phone 
    if(client->bytesAvailable()>0){ 
    //do stuff here, but the program doesnt get here, since bytesAvailable returns 0; 
} 

}

クライアント:

public SendPackage() { 
    try { 
     socket = new Socket(ServerIP, Port); 
     socket.setSoTimeout(60000); 
     output = new BufferedOutputStream(socket.getOutputStream()); 
     outwriter = new OutputStreamWriter(output); 
    } catch (ConnectException e) { 
     System.out.println("Server error, no connection established."); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

public void Send(BufferedImage img) { 

    try { 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     ImageIO.write(img, GUI.imageType, baos); 
     baos.flush(); 
     byte[] imgbyte = baos.toByteArray(); 
     System.out.println(imgbyte.length); 
     System.out.println("sending"); 

     outwriter.write(imgbyte.length); 
     outwriter.flush(); 
     // here i'd send the image, if i had a connection ... 
     output.flush(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

接続し、すべてが、送信しようとしたときにソケットが切断されたときのコードも私に伝え、罰金を構築しますだから私は接続が問題ではないと思う。 私はちょうどQtを使用し始めました。なぜあなたがこれがうまくいかないか考えていたら、私はそれを試して喜んでいます。

答えて

0
client->waitForConencted(); 

// At this point the client is connected, but it is likely that no data were received yet 

client->waitForReadyRead(-1); // <- Add this 

// Now there should be at least 1 byte available, unless waitForConencted or waitForReadyRead failed (you should check that) 

if(client->bytesAvailable() > 0) { 
    // ... 
} 

すべてのデータが一度に届くとは限りません。 TCPストリームはどのような方法でも断片化することができ、データはランダムなサイズの断片で受信されます。あなたはすべてを受け取るまで待って、読書を繰り返す必要があります。これはまた、あなたが何を受け取ったのか何とか知る必要があることを意味します。だから、どのくらいのデータが来るのか、それとも何とかそのデータの終わりを認識する必要があります。たとえば、データ転送の直後に接続を切断したり、データ長を最初に送信したりすることができます。あなたのアプリケーションによって異なります。

また、QIDevice::readyReadシグナルを見ると、非同期での読み込みを処理できます。

+0

実際には、while(connected)ループを読み込もうとしています。私はそれに言及するのを忘れていた。 – Kijata

+0

であり、サーバーは実際のアプリケーションの背後にある別のスレッドで実行されているため、タイミングは問題にはなりません。 – Kijata

+0

さて、あなたは 'QIDevice :: readyRead'を考慮する必要はありません。しかし、私の応答はまだ有効です - 私はあなたがデータをすぐに取得しようとしていると思います。 'waitForReadyRead'を追加するだけで、何らかのデータが表示されるはずです。 – michalsrb

関連する問題