Qt的tcpserver demo

mainwindow.cpp

  1. #include "mainwindow.h"  
  2. #include "ui_mainwindow.h"  
  3.   
  4. MainWindow::MainWindow(QWidget *parent) :  
  5.     QMainWindow(parent),  
  6.     ui(new Ui::MainWindow)  
  7. {  
  8.     ui->setupUi(this);  
  9.     this->ininServer();  
  10. }  
  11.   
  12. MainWindow::~MainWindow()  
  13. {  
  14.     delete ui;  
  15. }  
  16. void MainWindow::ininServer()  
  17. {  
  18.     this->listenSocket =new QTcpServer;  
  19.     this->listenSocket->listen(QHostAddress::Any,8888);  
  20.     QObject::connect(this->listenSocket,SIGNAL(newConnection()),this,SLOT(processConnection()));  
  21. }  
  22.   
  23. void MainWindow::processConnection()  
  24. {  
  25.      this->readWriteSocket =this->listenSocket->nextPendingConnection();  
  26.      QObject::connect(this->readWriteSocket,SIGNAL(readyRead()),this,SLOT(processText()));  
  27. }  
  28.   
  29. void MainWindow::processText()  
  30. {  
  31.     this->globalString+=this->readWriteSocket->readAll();  
  32.       ui->textEdit->setText(this->globalString);  
  33. }  

 

 

 

mainwindow.h

  1. #ifndef MAINWINDOW_H  
  2. #define MAINWINDOW_H  
  3.   
  4. #include <QMainWindow>  
  5. #include <QtNetwork/QTcpServer>  
  6. #include <QtNetwork/QHostAddress>  
  7. #include <QtNetwork/QTcpSocket>  
  8.   
  9. namespace Ui {  
  10.     class MainWindow;  
  11. }  
  12.   
  13. class MainWindow : public QMainWindow  
  14. {  
  15.     Q_OBJECT  
  16.   
  17. public:  
  18.     explicit MainWindow(QWidget *parent = 0);  
  19.     ~MainWindow();  
  20.     void ininServer();  
  21.   
  22. private:  
  23.     Ui::MainWindow *ui;  
  24.     QString globalString;  
  25.     QTcpServer   *listenSocket;  // 侦听套接字  
  26.     QTcpSocket   *readWriteSocket;//读写套接字  
  27. private slots:  
  28.     void  processConnection();  
  29.     void  processText();  
  30.   
  31. };  
  32.   
  33. #endif // MAINWINDOW_H  

 

 

 

main.cpp

  1. #include <QtGui/QApplication>  
  2. #include "mainwindow.h"  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     QApplication a(argc, argv);  
  7.     MainWindow w;  
  8.     w.show();  
  9.   
  10.     return a.exec();  
  11. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值