基本流程
QT += core gui network
#include "tcp.h"
#include "ui_tcp.h"
#include <QDebug> Tcp::Tcp(QWidget *parent) :
QWidget(parent),
ui(new Ui::Tcp)
{
ui->setupUi(this);
// ui init
ui->ip_edit->setText("127.0.0.1");
ui->port_edit->setText("");
// 实例化
server = new QTcpServer(this);
// 监听
server->listen(QHostAddress("127.0.0.1"),);
// 新的链接
connect(server, &QTcpServer::newConnection, this, [=](){
// 接收客户端套接字对象
// sock_addr 结构体 == 类 QTcpSocket
conn = server->nextPendingConnection();
ui->log_text->append("有新的链接");
// 接收数据
connect(conn,&QTcpSocket::readyRead, this, [=](){
QByteArray array = conn->readAll();
ui->log_text->append(array);
}); });
connect(ui->send, &QPushButton::clicked, this, [=](){
// 发送数据 QTextEdit
conn->write(ui->input_text->toPlainText().toUtf8());
ui->log_text->append("Me Say: " + ui->input_text->toPlainText());
ui->input_text->clear();
}); } Tcp::~Tcp()
{
delete ui;
}
server.cpp
#ifndef TCP_H
#define TCP_H #include <QWidget>
#include <QTcpSocket>
#include <QTcpServer> namespace Ui {
class Tcp;
} class Tcp : public QWidget
{
Q_OBJECT public:
explicit Tcp(QWidget *parent = nullptr);
~Tcp(); private:
Ui::Tcp *ui; QTcpServer *server;
QTcpSocket *conn;
}; #endif // TCP_H
server.h
#include "client.h"
#include "ui_client.h" Client::Client(QWidget *parent) :
QWidget(parent),
ui(new Ui::Client)
{
ui->setupUi(this);
// ui init
ui->cip_edit->setText("127.0.0.1");
ui->cport_edit->setText("");
// 实例化
client = new QTcpSocket(this);
// 链接服务器
client->connectToHost(QHostAddress("127.0.0.1"),); // 接收数据
connect(client, &QTcpSocket::readyRead, this, [=](){
QByteArray array = client->readAll();
ui->clog_text->append(array);
}); connect(ui->csend, &QPushButton::clicked, this, [=](){
client->write(ui->cinput_text->toPlainText().toUtf8());
ui->clog_text->append("Me Say: " + ui->cinput_text->toPlainText().toUtf8());
ui->cinput_text->clear();
}); } Client::~Client()
{
delete ui;
}
client.cpp
#ifndef CLIENT_H
#define CLIENT_H #include <QWidget>
#include <QTcpServer>
#include <QTcpSocket> namespace Ui {
class Client;
} class Client : public QWidget
{
Q_OBJECT public:
explicit Client(QWidget *parent = nullptr);
~Client(); private:
Ui::Client *ui; QTcpSocket* client;
}; #endif // CLIENT_H
client.h