我正在做一個簡單的服務器客戶端應用程序。但是,客戶端從服務器端獲得了一些未定義的行爲。在檢索錯誤代碼後,我開始知道服務器切斷了連接。Qt - QTcpserver無法正常工作
這是服務器端的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"
這是客戶端的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();
}
這是親文件(兩者相同)
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
SOURCES += main.cpp
QT += network
我找不到爲什麼服務器端正在切斷連接。如果有人幫我找出原因,我會感謝他們。
注:我用的Qt 4.7.2在Windows平臺
你的答案是「牛眼」。我將在服務器端QTcpSocket中使用其他一些機制,例如「waitForReadyRead」,以避免立即退出。因爲GUI是這個應用程序的核心。 – prabhakaran