2016-12-06 174 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

其实,即时尝试阅读一段时间(连接)循环。我忘了提到这一点。 – Kijata

+0

并且服务器在实际应用程序后面的另一个线程中运行,因此时间安排并不重要。 – Kijata

+0

好的,那么你不需要考虑'QIDevice :: readyRead'。但是我的回答仍然有效 - 我认为你只是尽可能快地获取数据。只需添加'waitForReadyRead',并在返回时您应该看到一些数据。 – michalsrb