客户端:
client.pro
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
FORMS += \
widget.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpSocket>
#include <QMessageBox>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_connectbtn_clicked();
void on_sendbtn_clicked();
void on_disconnectbtn_clicked();
public slots:
void connected_slot();
void readyRead_slot();
void disconnected_slot();
private:
Ui::Widget *ui;
//实例化一个客户端指针
QTcpSocket *socket;
//定义一个存放用户名的变量
QString userName;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, socket(new QTcpSocket(this))//客户端指针实例化空间
{
ui->setupUi(this);
//初始化界面设置
ui->msgEdit->setEnabled(false);
ui->sendbtn->setEnabled(false);
ui->disconnectbtn->setEnabled(false);
//如果成功连接到服务器,客户端就会自动发送connected信号
//我们就可以将该信号连接到自定义的槽函数
//由于只需要连接一次,所以连接函数写在构造函数中
connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);
//如果服务器发来数据,那么客户端就会自动发射一个readyRead信号
//我们就可以将该信号连接到自定义的槽函数
//由于只需要连接一次,所以连接函数写在构造函数中
connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
//如果成功断开连接,那么客户端就会自动发射一个disconnected信号
//我们就可以将该信号连接到自定义的槽函数
//由于只需要连接一次,所以连接函数写在构造函数中
connect(socket,&QTcpSocket::disconnected,this,&Widget::disconnected_slot);
}
Widget::~Widget()
{
delete ui;
}
//连接服务器按钮对应槽函数处理
void Widget::on_connectbtn_clicked()
{
//获取UI界面上的IP和端口号
QString ip=ui->ipEdit->text();
quint16 port=ui->portEdit->text().toUInt();//将字符串转换成整型
//让客户端连接服务器
socket->connectToHost(ip,port);
}
//connected信号对应的槽函数实现
void Widget::connected_slot()
{
QMessageBox::information(this,"","连接服务器成功!");
userName=ui->usernameEdit->text();
//组织下语言
QString msg=userName + ":进入聊天室";
//告诉服务器 我来了
socket->write(msg.toLocal8Bit());
ui->msgEdit->setEnabled(true);
ui->sendbtn->setEnabled(true);
ui->disconnectbtn->setEnabled(true);
ui->usernameEdit->setEnabled(false);
ui->ipEdit->setEnabled(false);
ui->portEdit->setEnabled(false);
ui->connectbtn->setEnabled(false);
}
//发送按钮对应槽函数处理
void Widget::on_sendbtn_clicked()
{
//获取UI界面文本
QString msg=ui->msgEdit->text();
msg=userName + ":" + msg;
// 将发送框清空
ui->msgEdit->clear();
//将信息发送给服务器
socket->write(msg.toLocal8Bit());
}
//readyRead信号对应的槽函数
void Widget::readyRead_slot()
{
//读取服务器发来数据
QByteArray msg=socket->readAll();
//将读取到的信息放入UI界面
ui->listWidget->addItem(QString::fromLocal8Bit(msg));
}
//disconnected对应的槽函数实现
void Widget::disconnected_slot()
{
ui->msgEdit->setEnabled(false);
ui->sendbtn->setEnabled(false);
ui->disconnectbtn->setEnabled(false);
ui->usernameEdit->setEnabled(true);
ui->ipEdit->setEnabled(true);
ui->portEdit->setEnabled(true);
ui->connectbtn->setEnabled(true);
}
//断开连接按钮对应槽函数
void Widget::on_disconnectbtn_clicked()
{
//告诉服务器 我走了
QString msg=userName + ":离开聊天室";
socket->write(msg.toLocal8Bit());
//让客户端和服务器断开连接
socket->disconnectFromHost();
}
服务器:
server.pro
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
FORMS += \
widget.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>//服务器类
#include <QMessageBox>
#include <QLineEdit>
#include <QDebug>
#include <QList>
#include <QTcpSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_startbtn_clicked();
void newConnection_slot();
void readyRead_slot();//readRead信号对应的槽函数
private:
Ui::Widget *ui;
//实例化一个 服务器指针
QTcpServer *server;
//存放客户端套接字的容器
QList <QTcpSocket *> socketList;
//实例化一个 客户端指针
QTcpSocket *socket;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, server(new QTcpServer(this))
, socket(new QTcpSocket(this))
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
//启动服务器按钮对应的槽函数
void Widget::on_startbtn_clicked()
{
//获取ui界面上端口号
quint16 port=ui->portedit->text().toUInt();//将字符串转换成整型
//让服务器设置监听
if(server->listen(QHostAddress::Any,port))
{
//监听成功---启动成功
QMessageBox::information(this,"","启动服务器成功");
}
else
{
//监听失败
QMessageBox::information(this,"","启动服务器失败");
return;//终止程序
}
//将该信号连接到自定义的槽函数
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
//newConnection信号对应的槽函数处理
void Widget::newConnection_slot()
{
qDebug() << "有新的客户端连接";
//获取最新连接的客户端套接字
QTcpSocket *s=server->nextPendingConnection();
//放入客户端容器中
socketList.push_back(s);
//程序运行至此,说明服务器端和客户端已经建立了连接 如果有客户端发来数据,那么客户端就会自动发射一个readyread信号
//我们就可以将该信号连接到自定义槽函数,读取客户端数据
connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
//readRead信号对应的槽函数实现
void Widget::readyRead_slot()
{
//遍历客户端容器,移除无效客户端
for(int i=0;i<socketList.count();i++)
{
//判断连接状态
if(socketList.at(i)->state()==0)
{
socketList.removeAt(i);//通过下标删除
}
}
//遍历客户端容器,有哪些客户端有带读数据
for(int i=0;i<socketList.count();i++)
{
//bytesAvailable()可以求出带读数据的大小
if(socketList.at(i)->bytesAvailable()!=0)
{
//读取数据
QByteArray msg=socketList.at(i)->readAll();
//将读取到的数据放入ui界面上
ui->listWidget->addItem(QString::fromLocal8Bit(msg));
//将数据广播给所有人
for(int j=0;j<socketList.count();j++)
{
socketList.at(j)->write(msg);
}
}
}
}
*******************代码来自上海华清远见C++课程老师周锁琴************************