qt服务器搭建

6 篇文章 0 订阅
3 篇文章 0 订阅

第一步:前奏工作

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

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

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

                             QTcpSocket cli; //客户端对象

 

第二步:编程

1、.h文件

 
  1. #ifndef DIALOG_H

  2. #define DIALOG_H

  3.  
  4. #include <QDialog>

  5. #include <QTcpServer>

  6. #include <QTcpSocket>

  7.  
  8.  
  9. namespace Ui {

  10. class Dialog;

  11. }

  12.  
  13. class Dialog : public QDialog

  14. {

  15. Q_OBJECT

  16.  
  17. public:

  18. explicit Dialog(QWidget *parent = 0);

  19. ~Dialog();

  20.  
  21. private:

  22. Ui::Dialog *ui;

  23.  
  24. QTcpServer *ser;

  25.  
  26. QTcpSocket *cli;

  27. };

  28.  
  29. #endif // DIALOG_H

2、cpp文件

 
  1. #include "dialog.h"

  2. #include "ui_dialog.h"

  3. #include <QDebug>

  4.  
  5.  
  6. Dialog::Dialog(QWidget *parent) :

  7. QDialog(parent),

  8. ui(new Ui::Dialog)

  9. {

  10. ui->setupUi(this);

  11.  
  12. //creat a server object

  13. ser = new QTcpServer(this);

  14.  
  15. //set server object to listen client

  16. //set server's ip to be the same as host

  17. //set server's port to be 8888

  18. ser->listen(QHostAddress::AnyIPv4,8888);

  19.  
  20. connect(ser,&QTcpServer::newConnection,

  21.  
  22. [=]()

  23. {

  24. //get cliet's sockfd

  25. cli = ser->nextPendingConnection();

  26.  
  27. //get client's ip and port

  28.  
  29. QString cli_ip = cli->peerAddress().toString();

  30. quint16 cli_port = cli->peerPort();

  31. QString temp = QString("[%1:%2 connect success]").arg(cli_ip).arg(cli_port);

  32.  
  33.  
  34. qDebug() << temp;

  35. }

  36. );

  37.  
  38.  
  39. }

  40.  
  41. Dialog::~Dialog()

  42. {

  43. delete ui;

  44. }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值