QT中TCP服务器实现
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, tcpServer(new QTcpServer(this))
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_StartBtn_clicked()
{
//获取ui界面上的端口号
quint16 port = ui->PortEdit->text().toUInt();
//让服务器设置为监听模式
if(tcpServer->listen(QHostAddress::Any, port)){
QMessageBox::information(
this,
"",
"启动服务器成功"
);
}else{
QMessageBox::information(
this,
"",
"启动服务器失败"
);
return;
}
//此时服务器已经设置好监听,如果有客户端发来连接,那么服务器就会自动发射一个newConnect信号
connect(tcpServer, &QTcpServer::newConnection, this, &Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
QTcpSocket *s = tcpServer->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){
QByteArray msg = socketList.at(i)->readAll();
ui->ChatWidget->addItem(QString::fromLocal8Bit(msg));
//将数据广播给所有客户端
for(int j=0; j<socketList.count(); j++){
socketList.at(j)->write(msg);
}
}
}
}