qt搭建服務器

第一步:前奏工作

     1、  pro文件添加類庫 network,Qt  += core gui network 。

      2、dialog.h 或者其他中 添加頭文件: #include <QTcpServer> 和 #include <QTcpSocket>。

     3、定義服務器和客戶端對象:QTcpServer ser;   //服務器對象

                             QTcpSocket cli; //客戶端對象

 

第二步:編程

1、.h文件

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QTcpServer>
#include <QTcpSocket>


namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

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

private:
    Ui::Dialog *ui;

    QTcpServer *ser;

    QTcpSocket *cli;
};

#endif // DIALOG_H

2、cpp文件

#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>


Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    //creat a server object
    ser = new QTcpServer(this);

    //set server object to listen client
    //set server's ip  to be the same as host
    //set server's port to be 8888
    ser->listen(QHostAddress::AnyIPv4,8888);

    connect(ser,&QTcpServer::newConnection,

            [=]()
           {
              //get cliet's sockfd
              cli = ser->nextPendingConnection();

              //get client's ip and port

              QString cli_ip = cli->peerAddress().toString();
              quint16 cli_port = cli->peerPort();
              QString temp = QString("[%1:%2 connect success]").arg(cli_ip).arg(cli_port);


              qDebug() << temp;
            }
            );


}

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

 

 

   

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章