I am doing a simple server-client application. But, the client gets some undefined behaviour from the server side. After I retrieved the error code, I came to know that the server cut the connection.
This is server-side main.cpp
#include <QApplication>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
class MyMessageBox:public QMessageBox
{
public:
MyMessageBox(std::string message,QWidget *parent=0):QMessageBox(QMessageBox::NoIcon,QString("ErrorMessage"),QString(message.c_str()),QMessageBox::Ok,parent,Qt::Widget)
{
}
};
class My_Server:public QTcpServer
{
Q_OBJECT
public:
My_Server();
public slots:
void on_Connection();
};
My_Server::My_Server():QTcpServer()
{
connect(this,SIGNAL(newConnection()),this,SLOT(on_Connection()));
}
void My_Server::on_Connection()
{
MyMessageBox mm("Connection Established");
mm.exec();
QTcpSocket * my_Socket = this->nextPendingConnection();
my_Socket->waitForBytesWritten(30000);
QByteArray block("Hi all");
my_Socket->write(block);
}
int main(int argc,char * argv[])
{
QApplication app(argc,argv);
My_Server tcp_Server;
tcp_Server.listen(QHostAddress("127.0.0.1"),15000);
return app.exec();
}
#include "main.moc"
This is client-side main.cpp
#include <QApplication>
#include <QDataStream>
#include <QFile>
#include <QFileDialog>
#include <QHostAddress>
#include <QMessageBox>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
class MyMessageBox:public QMessageBox
{
public:
MyMessageBox(std::string message,QWidget *parent=0):QMessageBox(QMessageBox::NoIcon,QString("ErrorMessage"),QString(message.c_str()),QMessageBox::Ok,parent,Qt::Widget)
{
}
};
int main(int argc,char * argv[])
{
QApplication app(argc,argv);
QTcpSocket client_Socket;
client_Socket.connectToHost(QHostAddress("127.0.0.1"),15000);
QDataStream in(&client_Socket);
in.setVersion(QDataStream::Qt_4_7);
client_Socket.waitForReadyRead(30000);
char buf[100]={'\0'};
client_Socket.read(buf,(quint16)sizeof(buf));
QString nothing(buf);
MyMessageBox mm((QString("++ ")+nothing+" ++").toStdString());
mm.exec();
MyMessageBox mn(QString::number(client_Socket.error()).toStdString());
mn.exec();
return app.exec();
}
This is the pro file( same for both)
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
SOURCES += main.cpp
QT += network
I can’t find out that why the server side is cutting the connection. If anybody help me to find out the cause, I will be thankful to them.
Note: I am using Qt-4.7.2 in windows platform
The connection is getting closed because your server is exiting right after it’s sent that message.
This is probably because you’re using
QApplication, but don’t actually have a long-lasting GUI widget. So the event loop stops short once you’ve finished displaying that first dialog box.Try either:
QCoreApplicationon the server side instead. (And don’t start a message box – no GUI allowed with QCoreApplication.)