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;
}

 

 

   

 

 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值