3
我在Qt中編寫了一個客戶端服務器程序,客戶端向服務器發送一些消息,但在編譯期間,「startserver」函數無法運行,並且出現以下錯誤:無法啓動服務器。你能說說問題在哪裏嗎?運行時錯誤:無法啓動服務器
「的main.cpp」
#include <QApplication>
#include "mythread.h"
#include "myserver.h"
#include "QtSql/QtSql"
#include "QMessageBox"
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
myserver server;
server.startserver();
MainWindow w;
w.show();
return a.exec();
}
「myserver.h」
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QMainWindow>
#include "QTcpServer"
#include "mythread.h"
#include "QTcpSocket"
namespace Ui
{
class myserver;
}
class myserver : public QObject
{
Q_OBJECT
public:
server(QObject * parent = 0);
explicit myserver(QObject *parent = 0);
void startserver();
public slots:
void acceptConnection();
protected:
void incomingConnections(qintptr socketDescriptor);
QTcpSocket* c_client;
QTcpServer s_server;
private:
qintptr socketDescriptor;
};
#endif
「myserver.cpp」
#include "myserver.h"
#include "mythread.h"
myserver::myserver(QObject *parent) :
QObject(parent)
{
}
void myserver::startserver()
{
int port = 1234;
if(s_server.listen(QHostAddress::Any, port))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening to port " ;
}
}
void myserver::incomingConnections(qintptr socketDescriptor)
{
mythread *thread = new mythread(socketDescriptor,this);
qDebug() << socketDescriptor << " Connecting...";
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void myserver::acceptConnection()
{
c_client = s_server.nextPendingConnection();
connect(c_client,SIGNAL(readyRead()),this, SLOT(startRead()));
qDebug() << " Connecting...";
}
A‘編譯器錯誤’是從* *編譯錯誤,是你得到當你* *構建你的程序。當你運行它時,你得到的信息來自已編譯和鏈接的程序。 –
至於*爲什麼*你得到的錯誤信息,你真的應該嘗試和[打印你得到的基礎錯誤](http://doc.qt.io/qt-5/qtcpserver.html#errorString),可能有聽衆呼叫失敗的原因很多(包括其他人使用該端口,您是否嘗試過使用另一個端口號?) –
是的..確切地說,這是我的端口號。提前感謝 – Hanita