项目环境:Win10 Qt5.14
运行结果
TCP服务器
1.在.pro配置文件中加入
QT += network
2.修改头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTextEdit>
#include <QPushButton>
#include <QLabel>
#include <QMessageBox>
#include <QStyle>
#include <QComboBox>
#include <QSpinBox>
#include <QGroupBox>
#include <QLineEdit>
#include <QHostInfo>
#include <QPlainTextEdit>
#pragma execution_character_set("utf-8")
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
void createWidget();
QLabel *LabListen;//状态栏标签
QLabel *LabSocketState;//状态栏标签
QTcpServer *tcpServer; //TCP服务器
QTcpSocket *tcpSocket; //TCP通信得Socket
//QString getLocalIP();//获得本机IP地址
QStringList getLocalIP();//获得本机IP地址
QPushButton *btn_start;
QPushButton *btn_stop;
QPushButton *btn_clear;
QComboBox *comboIP;
QSpinBox *spinPort;
QLineEdit *editMsg;
QPushButton *btn_send;
QPlainTextEdit *plainTextEdit;
protected:
//void closeEvent(QCloseEvent *event);
public slots:
void on_actStart_triggered();
void on_actStop_triggered();
void on_btnSend_clicked();
void on_btnClear_clicked();
//自定义槽函数
void onNewConnection();//QTcpServer的newConnection()信号
void onSocketStateChange(QAbstractSocket::SocketState socketState);
void onClientConnected();//Client Socket connected
void onClientDisconnected();//Client Socket disconnected
void onSocketReadyRead();//读取socket传入的数据
};
#endif // WIDGET_H
3.c++文件
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
createWidget();
}
Widget::~Widget()
{
}
void Widget::createWidget(){
this->setFixedSize(600,500);
QGroupBox *groupBox_btn = new QGroupBox();
groupBox_btn->setParent(this);
groupBox_btn->setGeometry(20,20,560,80);
btn_start = new QPushButton(groupBox_btn);
btn_start->setGeometry(45,20,50,30);
btn_start->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
QLabel *label0 = new QLabel();
label0->setParent(groupBox_btn);
label0->setText("开始监听");
label0->setGeometry(20,50,100,30);
label0->setAlignment(Qt::AlignCenter);
btn_stop = new QPushButton(groupBox_btn);
btn_stop->setGeometry(155,20,50,30);
btn_stop->setIcon(style()->standardIcon(QStyle::SP_MediaStop));
btn_stop->setEnabled(false);
QLabel *label1 = new QLabel();
label1->setParent(groupBox_btn);
label1->setText("停止监听");
label1->setGeometry(130,50,100,30);
label1->setAlignment(Qt::AlignCenter);
btn_clear = new QPushButton(groupBox_btn);
btn_clear->setGeometry(265,20,50,30);
btn_clear->setIcon(style()->standardIcon(QStyle::SP_DialogResetButton));
QLabel *label2 = new QLabel();
label2->setParent(groupBox_btn);
label2->setText("清空文本");
label2->setGeometry(240,50,100,30);
label2->setAlignment(Qt::AlignCenter);
QLabel *label3 = new QLabel();
label3->setParent(this);
label3->setText("监听地址:");
label3->setGeometry(20,120,100,30);
label3->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
comboIP =new QComboBox(this);
comboIP->setGeometry(120,120,200,30);
//comboIP->addItem("");
comboIP->setEditable(true);//可编辑
QLabel *label4 = new QLabel(this);
label4->setText("监听端口:");
label4->setGeometry(350,120,100,30);
label4->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
spinPort = new QSpinBox(this);
spinPort->setRange(0,65535);
spinPort->setGeometry(450,120,100,30);
spinPort->setValue(8080);
editMsg = new QLineEdit(this);
editMsg->setGeometry(40,170,400,30);
btn_send = new QPushButton(this);
btn_send->setGeometry(450,170,100,30);
btn_send->setText("发送信息");
plainTextEdit = new QPlainTextEdit(this);
plainTextEdit->setGeometry(20,220,560,200);
LabListen = new QLabel(this);
LabListen->setText("监听状态:");
LabListen->setGeometry(20,440,200,30);
LabListen->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
LabSocketState = new QLabel(this);
LabSocketState->setText("scoket状态:");
LabSocketState->setGeometry(240,440,300,30);
LabSocketState->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
///
///
/*
QString localIP = getLocalIP();//本机IP
comboIP->addItem(localIP);
*/
QStringList localIP = getLocalIP();//本机IP
comboIP->addItem("127.0.0.1");
comboIP->addItems(localIP);
tcpServer = new QTcpServer(this);
tcpSocket = new QTcpSocket(this);
tcpSocket->abort();//取消原有连接
connect(btn_start,SIGNAL(clicked()),this,SLOT(on_actStart_triggered()));
connect(btn_stop,SIGNAL(clicked()),this,SLOT(on_actStop_triggered()));
connect(btn_clear,SIGNAL(clicked()),this,SLOT(on_btnClear_clicked()));
connect(btn_send,SIGNAL(clicked()),this,SLOT(on_btnSend_clicked()));
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
}
QStringList Widget::getLocalIP(){
//获得本机IPv4地址
QString hostName = QHostInfo::localHostName();//本地主机名
QHostInfo hostInfo = QHostInfo::fromName(hostName);
QStringList localIP;
QList<QHostAddress> addList=hostInfo.addresses();
if(!addList.isEmpty()){
for (int i=0;i<addList.count();i++) {
QHostAddress aHost = addList.at(i);
if(QAbstractSocket::IPv4Protocol==aHost.protocol()){
localIP<<aHost.toString();
}
}
}
return localIP;
}
/*
QString Widget::getLocalIP(){
//获得本机IPv4地址
QString hostName = QHostInfo::localHostName();//本地主机名
QHostInfo hostInfo = QHostInfo::fromName(hostName);
QString localIP="";
QList<QHostAddress> addList=hostInfo.addresses();
if(!addList.isEmpty()){
for (int i=0;i<addList.count();i++) {
QHostAddress aHost = addList.at(i);
if(QAbstractSocket::IPv4Protocol==aHost.protocol()){
localIP=aHost.toString();
break;
}
}
}
return localIP;
}
*/
void Widget::on_actStart_triggered(){
//开始监听
QString IP=comboIP->currentText();//IP地址
quint16 port=spinPort->value();//端口
QHostAddress addr(IP);
tcpServer->listen(addr,port);//开始监听
plainTextEdit->appendPlainText("**开始监听...");
plainTextEdit->appendPlainText("**服务器地址:"
+tcpServer->serverAddress().toString());
plainTextEdit->appendPlainText("**服务器端口:"
+QString::number(tcpServer->serverPort()));
btn_start->setEnabled(false);
btn_stop->setEnabled(true);
LabListen->setText("监听状态:正在监听");
}
void Widget::onNewConnection(){
tcpSocket = tcpServer->nextPendingConnection();//获取socket
//connect(tcpSocket,SIGNAL(connected()),this,SLOT(onClientConnected()));
onClientConnected();
connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(onClientDisconnected()));
connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
onSocketStateChange(tcpSocket->state());
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));
}
void Widget::onClientConnected(){
plainTextEdit->appendPlainText("**client socket connected");
plainTextEdit->appendPlainText("**peer address:"+
tcpSocket->peerAddress().toString());
plainTextEdit->appendPlainText("**peer port:"+
QString::number(tcpSocket->peerPort()));
}
void Widget::onClientDisconnected(){
//客户端断开连接时
plainTextEdit->appendPlainText("**client socket disconnected");
tcpSocket->deleteLater();
}
void Widget::onSocketStateChange(QAbstractSocket::SocketState socketState){
//socket状态变化时
switch (socketState) {
case QAbstractSocket::UnconnectedState:
LabSocketState->setText("scoket状态:UnconnectedState");
break;
case QAbstractSocket::HostLookupState:
LabSocketState->setText("scoket状态:HostLookupState");
break;
case QAbstractSocket::ConnectingState:
LabSocketState->setText("scoket状态:ConnectingState");
break;
case QAbstractSocket::ConnectedState:
LabSocketState->setText("scoket状态:ConnectedState");
break;
case QAbstractSocket::BoundState:
LabSocketState->setText("scoket状态:BoundState");
break;
case QAbstractSocket::ClosingState:
LabSocketState->setText("scoket状态:ClosingState");
break;
case QAbstractSocket::ListeningState:
LabSocketState->setText("scoket状态:ListeningState");
break;
}
}
void Widget::on_actStop_triggered(){
//停止监听
if(tcpServer->isListening())//tcpServer正在监听
{
tcpServer->close();//停止监听
btn_start->setEnabled(true);
btn_stop->setEnabled(false);
LabListen->setText("监听状态:已停止监听");
//
//
if(tcpSocket->state()==QAbstractSocket::ConnectedState){
tcpSocket->disconnectFromHost();
}
}
}
void Widget::on_btnSend_clicked(){
//发送一行字符串,以换行符结束
QString msg = editMsg->text();
plainTextEdit->appendPlainText("[out] "+msg);
editMsg->clear();
editMsg->setFocus();
QByteArray str=msg.toUtf8();
str.append('\n');//添加一个换行符
tcpSocket->write(str);
}
void Widget::on_btnClear_clicked(){
//清除文本
plainTextEdit->clear();
}
void Widget::onSocketReadyRead(){
//读取缓冲区行文本
while (tcpSocket->canReadLine()) {
QString data = tcpSocket->readLine();
plainTextEdit->appendPlainText("[in] "+data);
//qDebug()<<data;
//plainTextEdit->appendPlainText("[in] "+tcpSocket->readLine());
}
}
TCP客户端
1..pro加入
QT += network
2.头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
//#include <QTcpServer>
#include <QTcpSocket>
#include <QTextEdit>
#include <QPushButton>
#include <QLabel>
#include <QMessageBox>
#include <QStyle>
#include <QComboBox>
#include <QSpinBox>
#include <QGroupBox>
#include <QLineEdit>
#include <QHostInfo>
#include <QPlainTextEdit>
#pragma execution_character_set("utf-8")
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
void createWidget();
QPushButton *btn_Connect;
QPushButton *btn_Disconnect;
QPushButton *btn_clear;
QComboBox *comboServer;
QSpinBox *spinPort;
QLineEdit *editMsg;
QPushButton *btn_send;
QPlainTextEdit *plainTextEdit;
QTcpSocket *tcpClient; //socket
QLabel *LabSocketState; //状态栏显示标签
//QString getLocalIP();//获得本机IP地址
QStringList getLocalIP();//获得本机IP地址
protected:
//void closeEvent(QCloseEvent *event);
private slots:
void on_actConnect_triggered();
void on_actDisconnect_triggered();
void on_btnSend_clicked();
void on_btnClear_clicked();
//自定义槽函数
void onConnected();
void onDisconnected();
void onSocketStateChange(QAbstractSocket::SocketState socketState);
void onSocketReadyRead();
};
#endif // WIDGET_H
3.C++文件
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
createWidget();
}
Widget::~Widget()
{
}
void Widget::createWidget(){
//this->setFixedSize(600,600);
this->setFixedSize(600,500);
QGroupBox *groupBox_btn = new QGroupBox();
groupBox_btn->setParent(this);
groupBox_btn->setGeometry(20,20,560,80);
btn_Connect = new QPushButton(groupBox_btn);
btn_Connect->setGeometry(45,20,50,30);
btn_Connect->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
QLabel *label0 = new QLabel();
label0->setParent(groupBox_btn);
label0->setText("连接服务器");
label0->setGeometry(20,50,100,30);
label0->setAlignment(Qt::AlignCenter);
btn_Disconnect = new QPushButton(groupBox_btn);
btn_Disconnect->setGeometry(155,20,50,30);
btn_Disconnect->setIcon(style()->standardIcon(QStyle::SP_MediaStop));
btn_Disconnect->setEnabled(false);
QLabel *label1 = new QLabel();
label1->setParent(groupBox_btn);
label1->setText("断开连接");
label1->setGeometry(130,50,100,30);
label1->setAlignment(Qt::AlignCenter);
btn_clear = new QPushButton(groupBox_btn);
btn_clear->setGeometry(265,20,50,30);
btn_clear->setIcon(style()->standardIcon(QStyle::SP_DialogResetButton));
QLabel *label2 = new QLabel();
label2->setParent(groupBox_btn);
label2->setText("清空文本");
label2->setGeometry(240,50,100,30);
label2->setAlignment(Qt::AlignCenter);
QLabel *label3 = new QLabel();
label3->setParent(this);
label3->setText("服务器地址:");
label3->setGeometry(20,120,100,30);
label3->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
comboServer =new QComboBox(this);
comboServer->setGeometry(120,120,200,30);
comboServer->setEditable(true);//可编辑
QLabel *label4 = new QLabel(this);
//label3->setParent(this);
label4->setText("端口:");
label4->setGeometry(350,120,100,30);
label4->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
spinPort = new QSpinBox(this);
spinPort->setRange(0,65535);
spinPort->setGeometry(450,120,100,30);
spinPort->setValue(8080);
editMsg = new QLineEdit(this);
editMsg->setGeometry(40,170,400,30);
btn_send = new QPushButton(this);
btn_send->setGeometry(450,170,100,30);
btn_send->setText("发送信息");
plainTextEdit = new QPlainTextEdit(this);
plainTextEdit->setGeometry(20,220,560,200);
LabSocketState = new QLabel(this);
LabSocketState->setText("scoket状态:");
LabSocketState->setGeometry(20,440,300,30);
LabSocketState->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
//
tcpClient = new QTcpSocket(this);//创建socket变量
tcpClient->abort();
/*
QString localIP = getLocalIP();
comboServer->addItem(localIP);
*/
QStringList localIP = getLocalIP();//本机IP
comboServer->addItem("");
comboServer->addItem("127.0.0.1");
comboServer->addItems(localIP);
connect(btn_Connect,SIGNAL(clicked()),this,SLOT(on_actConnect_triggered()));
connect(btn_Disconnect,SIGNAL(clicked()),this,SLOT(on_actDisconnect_triggered()));
connect(btn_send,SIGNAL(clicked()),this,SLOT(on_btnSend_clicked()));
connect(btn_clear,SIGNAL(clicked()),this,SLOT(on_btnClear_clicked()));
///
connect(tcpClient,SIGNAL(connected()),this,SLOT(onConnected()));
connect(tcpClient,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
connect(tcpClient,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
connect(tcpClient,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));
}
/*
QString Widget::getLocalIP(){
//获得本机IPv4地址
QString hostName = QHostInfo::localHostName();//本地主机名
QHostInfo hostInfo = QHostInfo::fromName(hostName);
QString localIP="";
QList<QHostAddress> addList=hostInfo.addresses();
if(!addList.isEmpty()){
for (int i=0;i<addList.count();i++) {
QHostAddress aHost = addList.at(i);
if(QAbstractSocket::IPv4Protocol==aHost.protocol()){
localIP=aHost.toString();
break;
}
}
}
return localIP;
}
*/
QStringList Widget::getLocalIP(){
//获得本机IPv4地址
QString hostName = QHostInfo::localHostName();//本地主机名
QHostInfo hostInfo = QHostInfo::fromName(hostName);
QStringList localIP;
QList<QHostAddress> addList=hostInfo.addresses();
if(!addList.isEmpty()){
for (int i=0;i<addList.count();i++) {
QHostAddress aHost = addList.at(i);
if(QAbstractSocket::IPv4Protocol==aHost.protocol()){
localIP<<aHost.toString();
//break;
}
}
}
return localIP;
}
void Widget::on_actConnect_triggered(){
//连接到服务器按钮
QString addr = comboServer->currentText();
quint16 port = spinPort->value();
tcpClient->connectToHost(addr,port);
}
void Widget::on_actDisconnect_triggered(){
//"断开连接"按钮
if(tcpClient->state()==QAbstractSocket::ConnectedState){
tcpClient->disconnectFromHost();
}
}
void Widget::onConnected(){
//connected()信号槽函数
plainTextEdit->appendPlainText("**已连接到服务器");
plainTextEdit->appendPlainText("**peer address:"+
tcpClient->peerAddress().toString());
plainTextEdit->appendPlainText("**peer port:"+
QString::number(tcpClient->peerPort()));
btn_Connect->setEnabled(false);
btn_Disconnect->setEnabled(true);
}
void Widget::onDisconnected(){
//disconnected()//信号槽函数
plainTextEdit->appendPlainText("**已断开与服务器的连接");
btn_Connect->setEnabled(true);
btn_Disconnect->setEnabled(false);
}
void Widget::on_btnSend_clicked(){
//发送一行字符串,以换行符结束
QString msg = editMsg->text();
plainTextEdit->appendPlainText("[out] "+msg);
editMsg->clear();
editMsg->setFocus();
QByteArray str=msg.toUtf8();
str.append('\n');//添加一个换行符
tcpClient->write(str);
}
void Widget::on_btnClear_clicked(){
//清除文本
plainTextEdit->clear();
}
void Widget::onSocketStateChange(QAbstractSocket::SocketState socketState){
//socket状态变化时
switch (socketState) {
case QAbstractSocket::UnconnectedState:
LabSocketState->setText("scoket状态:UnconnectedState");
break;
case QAbstractSocket::HostLookupState:
LabSocketState->setText("scoket状态:HostLookupState");
break;
case QAbstractSocket::ConnectingState:
LabSocketState->setText("scoket状态:ConnectingState");
break;
case QAbstractSocket::ConnectedState:
LabSocketState->setText("scoket状态:ConnectedState");
break;
case QAbstractSocket::BoundState:
LabSocketState->setText("scoket状态:BoundState");
break;
case QAbstractSocket::ClosingState:
LabSocketState->setText("scoket状态:ClosingState");
break;
case QAbstractSocket::ListeningState:
LabSocketState->setText("scoket状态:ListeningState");
break;
}
}
void Widget::onSocketReadyRead(){
//readRead()信号槽函数
while (tcpClient->canReadLine()) {
plainTextEdit->appendPlainText("[in] "+tcpClient->readLine());
}
}