QT编程教程"TCP服务器和客户端"
1、打开QT程序,点击 New Project

2、接着下一步

3、取项目名字,保存项目路径,(不要有中文路径)

4、都选择默认下一步



5、然后QT程序就创建好了,接着点击ui设计师,在界面上添加控件

6、在界面上添加两个QTextEdit,用来显示数据和输入框,再添加两个PhsuButton按钮,用来发送数据和断开连接。

7、然后开始写代码,,在头文件里面,添加QTcpServer套接字和QtcpSocket通信套接字,在后缀名为pro项目文件里面添加 network 和CONFIG += C++11


8、然后在源文件里面填写相对应的代码即可完成服务器端;

9、然后创建客户端,过程和服务器端差不多,接着就是在UI界面上添加控件,然后转到槽,写上相应的代码即可完成客户端;

10、运行效果图如下:(想要源码的可以留下邮箱,我直接发给你,直接可以运行,都注释好了)

11、服务器代码:
#include "widget.h"#include "ui_widget.h"Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget){ ui->setupUi(this); tcpserver = NULL; tcpsocket =NULL; //监听套接字 tcpserver = new QTcpServer(this); tcpserver->listen(QHostAddress::Any,8888); setWindowTitle("服务器:8888"); //取窗口名字 tcpsocket = new QTcpSocket(this);//为什么指定父对象,让他自动回收空间 connect(tcpserver,&QTcpServer::newConnection, [=]() { //取出建立好的套接字 tcpsocket = tcpserver->nextPendingConnection(); //显示当前连接对象,获取对方的IP和端口 QString ip = tcpsocket->peerAddress().toString(); qint16 prot = tcpsocket->peerPort(); //组包,自定义格式显示 QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(prot); ui->textEditread->setText(temp); //显示对方发来的消息 connect(tcpsocket,&QTcpSocket::readyRead, [=]() { //从通信套接字中取出内容 QByteArray array = tcpsocket->readAll(); ui->textEditread->append(array); } ); } );}Widget::~Widget(){ delete ui;}void Widget::on_sendBtn_clicked(){ if(tcpsocket == NULL) { return; } else { //获取编辑区内容 QString str = ui->textwrite->toPlainText(); //给对方发生套接字,直接往socket里面写就行 tcpsocket->write(str.toUtf8().data()); }}void Widget::on_btnclose_clicked(){ tcpsocket->disconnectFromHost(); tcpsocket->close(); tcpsocket = NULL; this->close();}
12、客户端代码:
#include "clientmidget.h"#include "ui_clientmidget.h"#include <QHostAddress>ClientMidget::ClientMidget(QWidget *parent) : QWidget(parent), ui(new Ui::ClientMidget){ ui->setupUi(this); tcpsocket =NULL; setWindowTitle("客户端"); tcpsocket = new QTcpSocket(this); connect(tcpsocket,&QTcpSocket::connected, [=]() { ui->textEditread->setText("成功和服务器建立好连接"); } ); //收消息 connect(tcpsocket,&QTcpSocket::readyRead, [=]() { //获取对方发送的内容 QByteArray array = tcpsocket->readAll(); //追加到编辑区中 ui->textEditread->append(array); } );}ClientMidget::~ClientMidget(){ delete ui;}void ClientMidget::on_btnClient_clicked(){ //获取服务器的IP和端口 QString strip = ui->lineEditIP->text(); qint16 prot = ui->lineEditprot->text().toInt(); //主动和服务器建立连接 tcpsocket->connectToHost(QHostAddress(strip),prot);}void ClientMidget::on_btnsend_clicked(){ //获取编辑区的内容 QString str = ui->textEditwrite->toPlainText(); //发送数据 tcpsocket->write(str.toUtf8().data());}void ClientMidget::on_btnclose_clicked(){ //主动和对方断开连接 tcpsocket->disconnectFromHost();}