qt5 网络中的连接错误

Connection error in qt5 network

本文关键字:连接 错误 网络 qt5      更新时间:2023-10-16

我想做一个像MSN Messenger这样的程序,我已经将Qt5与网络一起使用,当我打开与本地服务器的新连接时,它不起作用,它给了我我的服务器没有连接我不知道原因

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void on_pushButton_clicked();
    void newConnection ();
private:
    Ui::MainWindow *ui;
    QTcpServer *server;
};
#endif // MAINWINDOW_H

主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server = new QTcpServer(this);
    connect(server , SIGNAL(newConnection()) , this , SLOT(newConnection()));
    if(server->listen(QHostAddress::Any , 5050))
    {
        ui->label->setText("Not Start");
    }
    else
    {
        ui->label->setText("Server Started Now");
    }
}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::newConnection()
{
    QTcpSocket *socket = server->nextPendingConnection();
    socket->write("Hello Islam");
    socket->flush();
    socket->waitForBytesWritten(3000);
    socket->close();
}
void MainWindow::on_pushButton_clicked()
{
    newConnection();
}

这用于调用库

#-------------------------------------------------
#
# Project created by QtCreator 2013-11-03T10:00:37
#
#-------------------------------------------------
QT       += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = TCPTEST
TEMPLATE = app

SOURCES += main.cpp
        mainwindow.cpp
HEADERS  += mainwindow.h
FORMS    += mainwindow.ui

我尝试在主窗口构造函数中调用新连接,但它不起作用

我认为错误在

if(server->listen(QHostAddress::Any , 1234))

它有效,但一定是

if(!server->listen(QHostAddress::Any , 1234))

启动服务器