QT TCP通信(client+server)
首先在.pro文件中引入network模块
QT += network #添加network模块
引入头文件
#include<QTcpServer>
#include<QTcpSocket>
编码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include<QTcpServer>
#include<QTcpSocket>
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_connect_btn_clicked();
void on_disconnect_btn_clicked();
void newconnection();
private:
QTcpServer *tcpserver = NULL;
QTcpSocket *tcpsocket = NULL;
Ui::MainWindow *ui;
};
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QDebug>
#pragma execution_character_set("utf-8")
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tcpserver = new QTcpServer(this);
tcpserver->listen(QHostAddress::LocalHost,7722);
connect(tcpserver,&QTcpServer::newConnection,this,[=]()->void{
tcpsocket=tcpserver->nextPendingConnection();
QString ip = tcpsocket->peerAddress().toString();
quint16 port=tcpsocket->peerPort();
qDebug()<<QString("[%1:%2] 客服端连接成功").arg(ip).arg(port);
connect(tcpsocket,&QTcpSocket::readyRead,this,[=]()->void{
qDebug()<<tcpsocket->readAll();
tcpsocket->write("hello i am server");
});
connect(tcpsocket,&QTcpSocket::disconnected,this,[=]()->void{
QString ip = tcpsocket->peerAddress().toString();
quint16 port=tcpsocket->peerPort();
qDebug()<<QString("[%1:%2] 断开连接").arg(ip).arg(port);
});
});
}
MainWindow::~MainWindow()
{
delete ui;
tcpsocket->disconnectFromHost();
tcpsocket->close();
tcpsocket= NULL;
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QTcpSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QTcpSocket *tcpsocket = NULL;
};
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tcpsocket =new QTcpSocket(this);
tcpsocket->connectToHost("127.0.0.1",7722);
tcpsocket->write("hello i am client ");
connect(tcpsocket,&QTcpSocket::readyRead,this,[=]()->void{
qDebug()<<tcpsocket->readAll();
});
}
MainWindow::~MainWindow()
{
delete ui;
}
运行截图