mainwindow.cpp
- #include "mainwindow.h"
- #include "ui_mainwindow.h"
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
- this->ininServer();
- }
- MainWindow::~MainWindow()
- {
- delete ui;
- }
- void MainWindow::ininServer()
- {
- this->listenSocket =new QTcpServer;
- this->listenSocket->listen(QHostAddress::Any,8888);
- QObject::connect(this->listenSocket,SIGNAL(newConnection()),this,SLOT(processConnection()));
- }
- void MainWindow::processConnection()
- {
- this->readWriteSocket =this->listenSocket->nextPendingConnection();
- QObject::connect(this->readWriteSocket,SIGNAL(readyRead()),this,SLOT(processText()));
- }
- void MainWindow::processText()
- {
- this->globalString+=this->readWriteSocket->readAll();
- ui->textEdit->setText(this->globalString);
- }
mainwindow.h
- #ifndef MAINWINDOW_H
- #define MAINWINDOW_H
- #include <QMainWindow>
- #include <QtNetwork/QTcpServer>
- #include <QtNetwork/QHostAddress>
- #include <QtNetwork/QTcpSocket>
- namespace Ui {
- class MainWindow;
- }
- class MainWindow : public QMainWindow
- {
- Q_OBJECT
- public:
- explicit MainWindow(QWidget *parent = 0);
- ~MainWindow();
- void ininServer();
- private:
- Ui::MainWindow *ui;
- QString globalString;
- QTcpServer *listenSocket; // 侦听套接字
- QTcpSocket *readWriteSocket;//读写套接字
- private slots:
- void processConnection();
- void processText();
- };
- #endif // MAINWINDOW_H
main.cpp
- #include <QtGui/QApplication>
- #include "mainwindow.h"
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- MainWindow w;
- w.show();
- return a.exec();
- }