QT TCP服務器


注意在.pro文件里加入一行

QT += network


.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void newconnected();
    void sendData();
    void recvData();
    void disconnected();

private:
    Ui::MainWindow *ui;
    QTcpServer *server;
    QTcpSocket *socket;
};

#endif // MAINWINDOW_H

 

.cpp文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->pushButton->setEnabled(false);
    server = new QTcpServer;
    socket = new QTcpSocket;
    if(!server->listen(QHostAddress::AnyIPv4,quint16(8888))){
        return;
    }
    connect(server,SIGNAL(newConnection()),this,SLOT(newconnected()));
    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(sendData()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::newconnected()
{
    if(server->hasPendingConnections()){  //如果服務端有一個待處理的連接,就返回真,否則返回假
        socket = server->nextPendingConnection();  //將下一個掛起的連接作為已連接的qtcsocket對象返回。
        if(!socket->isValid()){  //套接字是否有效
            return;
        }
        ui->label->setText("connect");
        ui->pushButton->setEnabled(true);
        connect(socket,SIGNAL(readyRead()),this,SLOT(recvData()));
        connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()));
    }
}

void MainWindow::sendData()
{
    QString str = ui->textEdit_2->toPlainText();
    socket->write(str.toStdString().c_str(),str.length());
}

void MainWindow::recvData()
{
    QByteArray str = socket->readAll();
    ui->textEdit->setText(str);
}

void MainWindow::disconnected()
{
    ui->label->setText("disconnect");
    ui->pushButton->setEnabled(false);
}

 

 

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM