[英]How to do Java tcp client <-> Qt tcp server socket communication
[英]Qt server / Java Client communication problems
我目前正在尝试在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,所以如果你们知道为什么这不起作用,我会很高兴尝试它。
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信号,它允许您异步处理读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.