Dmitry Dmitry - 9 months ago 33
Java Question

Server on java does not get message from Qt client

I have very simple java server:

int port = 2245;
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");

Socket incomingClient = ss.accept();
InputStream i = incomingClient.getInputStream();
OutputStream o = incomingClient.getOutputStream(); // Use it write to the Client Socket
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = new String();

while ((str = br.readLine())!=null){
System.out.println("str = " + str);
o.write(123); //("message from server");
}
} catch(Exception x) { x.printStackTrace(); }


And I have simple Qt client, that use QNetworkAccessManager

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QUrl url("http://127.0.0.1:2245");
url.port(6666);
QByteArray postData;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

QString postKey("SomeKey");
postData.append(postKey);
QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));


I declared in mainwindow.h in slot replyFinished

public slots:
void replyFinished(QNetworkReply* reply);


In best case Server get some headers like(POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded and others)

But on server I can not read my message from client
and client does not receive ANY response from java server

Answer Source

The correct code for Qt client is this:

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QUrl url("http://192.168.0.101:8000");
url.port(8000);

QByteArray postData;
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

QString postKey("some data");
postData.append(postKey);
QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));

manager->post(request, postData);

}

and to get response declare and implement the following slot

void MainWindow::replyFinished(QNetworkReply *reply){
qDebug() << "Status" << reply->errorString();
qDebug() << "Status" << reply->error();


     QByteArray data = reply->readAll(); //It's works!
     qDebug() << "data: " << data;

}

For server side I have used HttpServer, which is available in latest version of JDK