最简单明了的QT服务器搭建

第一步:前奏工作

     1、pro文件添加类库 network,Qt  += core gui network 。

     2、dialog.h 或者其他中 添加头文件: #include 和 #include

     3、定义服务器和客户端对象:QTcpServer ser;   //服务器对象

                                                      QTcpSocket cli; //客户端对象

 

第二步:编程

1、.h文件

#ifndef DIALOG_H
#define DIALOG_H
 
#include 
#include 
#include 
 
 
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 
 
 
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;
}

 

你可能感兴趣的:(QT,服务器)