qt5网络中的连接错误

时间:2013-11-03 08:33:06

标签: c++ qt sockets networking

我想制作一个像msn messenger这样的程序,我已经使用qt5与网络,当我打开与我的本地服务器的新连接时,它不起作用,它回复给我,我的服务器没有连接我不'知道原因

mainwindow.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

mainwindow.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

我试图在mainwindow构造函数中调用新连接,但它不起作用

1 个答案:

答案 0 :(得分:0)

我认为错误发生在

  

if(server-&gt; listen(QHostAddress :: Any,1234))

它有效,但必须

  

if(!server-&gt; listen(QHostAddress :: Any,1234))

让服务器启动