C++ Qt-QTcpserver工作不正常
我正在做一个简单的服务器客户端应用程序。但是,客户端从服务器端获得一些未定义的行为。在检索到错误代码后,我知道服务器切断了连接 这是服务器端main.cppC++ Qt-QTcpserver工作不正常,c++,windows,qt,network-programming,C++,Windows,Qt,Network Programming,我正在做一个简单的服务器客户端应用程序。但是,客户端从服务器端获得一些未定义的行为。在检索到错误代码后,我知道服务器切断了连接 这是服务器端main.cpp #include <QApplication> #include <QFile> #include <QFileDialog> #include <QMessageBox> #include <QtNetwork/QTcpServer> #include <QtNetwork
#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"
#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();
}
我不知道服务器端为什么要切断连接。如果有人帮我找出原因,我会感谢他们
注意:我正在windows平台中使用Qt-4.7.2,连接正在关闭,因为您的服务器在发送该消息后立即退出 这可能是因为您使用的是
QApplication
,但实际上没有持久的GUI小部件。因此,一旦完成第一个对话框的显示,事件循环就会短暂停止
尝试以下任一方法:
- 在服务器端使用
。(并且不要启动消息框-QCoreApplication不允许使用GUI。)QCoreApplication
- 为服务器提供一个负责启动TCP服务器的主窗口小部件
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
SOURCES += main.cpp
QT += network