Qt 中实现TCP 聊天服务器
大致流程
创建套接字服务器QTcpServer对象
通过QTcpServer对象设置监听,即QTcpServer::listen()
基于QTcpServer::newConnection()信号检测是否有新的客户端连接
如果有新的客户端连接 调用QTcpSocket *QTcpServer::nextPendingConnection()得到通信的套接字对象
使用通信的套接字对象QTcpSocket和客户端进行通信
.pro文件
QT += core gui network # 所需模块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
.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer> //??包含TCP服务器类
#include <QMessageBox> //消息对话框类
#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(); //声明一下客户端发射的readyRead()信号对应的槽函数
private:
Ui::Widget *ui;
QTcpServer *server; //创建一个套接字服务器QTcpServer对象 在构造函数初始化列表中初始化
QList<QTcpSocket *> socketList; //定义一个存放客户套接字的容器
};
#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();
}
.cpp文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
,server(new QTcpServer(this)) //初始化列表 初始化server
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_startBtn_clicked()
{
//定义一个 quint16 类型的变量port 接收 字符串端口转换成 整型的端口
quint16 port = ui->portEdit->text().toUInt();
//调用 QTcpServer类型的对象server里的listen函数,实现监听
if(server->listen(QHostAddress::Any,port))
{
//启动监听成功
QMessageBox::information(this,"","启动服务器成功");
}
else
{
//启动监听失败
QMessageBox::critical(this,"","启动服务器失败");
}
//此时服务器已经成功启动监听,如果有客户端发来连接,那么服务器端就会自动发射一个newConnection()的信号
//将该信号连接到自定义的槽函数中
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
//newConnection_slot()槽函数的实现
//有客户端连接时,服务器发射一个newConnection信号后,执行这个函数
void Widget::newConnection_slot()
{
//使用QTcpSocket *QTcpServer::nextPenddingConnection()函数得到通信的套接字对象
QTcpSocket *s = server->nextPendingConnection();
socketList.push_back(s); // 用尾插法将套接字放入链表
//如果有客户端发来数据,客户端就会自动发射一个readyRead信号,就可以将该信号连接到自定义的槽函数中
connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
//客户端发射信号对应的槽函数的实现
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++)
{
if(socketList.at(i)->bytesAvailable() != 0)
{
//!= 0 说明这些是有效数据
QByteArray msg = socketList.at(i)->readAll();
//将读取到的数据 放到ui界面上
ui->listWidget->addItem(QString::fromLocal8Bit(msg)); //fromlocal8bit() 将Windows的GBK字符转换为Qt的Unicode
//QString::Local8bit是本地操作系统设置的字符集编码
//将数据广播给所有客户端
for(int i=0; i<socketList.count(); i++)
{
socketList.at(i)->write(msg);
}
}
}
}