标签:top image 有一个 include alt 是否有效 list ima add
注意在.pro文件里加入一行
QT += network
.h文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QTcpServer> #include <QTcpSocket> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void newconnected(); void sendData(); void recvData(); void disconnected(); private: Ui::MainWindow *ui; QTcpServer *server; QTcpSocket *socket; }; #endif // MAINWINDOW_H
.cpp文件
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->pushButton->setEnabled(false); server = new QTcpServer; socket = new QTcpSocket; if(!server->listen(QHostAddress::AnyIPv4,quint16(8888))){ return; } connect(server,SIGNAL(newConnection()),this,SLOT(newconnected())); connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(sendData())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::newconnected() { if(server->hasPendingConnections()){ //如果服务端有一个待处理的连接,就返回真,否则返回假 socket = server->nextPendingConnection(); //将下一个挂起的连接作为已连接的qtcsocket对象返回。 if(!socket->isValid()){ //套接字是否有效 return; } ui->label->setText("connect"); ui->pushButton->setEnabled(true); connect(socket,SIGNAL(readyRead()),this,SLOT(recvData())); connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected())); } } void MainWindow::sendData() { QString str = ui->textEdit_2->toPlainText(); socket->write(str.toStdString().c_str(),str.length()); } void MainWindow::recvData() { QByteArray str = socket->readAll(); ui->textEdit->setText(str); } void MainWindow::disconnected() { ui->label->setText("disconnect"); ui->pushButton->setEnabled(false); }
结果:
标签:top image 有一个 include alt 是否有效 list ima add
原文地址:https://www.cnblogs.com/caozewen/p/12169231.html