今日任务:QT实现TCP服务器客户端搭建的代码,现象
ser:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server = new QTcpServer(this);
connect(server,&QTcpServer::newConnection,this,&Widget::newConnectionSlot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_startButton_clicked()
{
quint16 port = ui->portEdit->text().toUInt();
//监听客户端的连接请求
if(!server->listen(QHostAddress::Any,port)){
QMessageBox::information(this,"失败","监听失败");
return;
}else{
QMessageBox::information(this,"成功","服务器启动成功");
}
}
void Widget::newConnectionSlot()
{
//qDebug()<<"您有新的客户端发来请求";
QTcpSocket *s = server->nextPendingConnection();
clientList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::readyReadSlot);
}
void Widget::readyReadSlot()
{
for(int i = 0;i < clientList.size();i++){
//判断当前套接字是否有效连接
if(!clientList[i]->state()){
//将该套接字移除客户端容易
clientList.removeAt(i);
}
}
for(int i = 0;i < clientList.size();i++){
if(clientList[i]->bytesAvailable()){
//将该套接字的数据读取出来
QByteArray msg = clientList[i]->readAll();
ui->msgWidget->addItem(QString::fromLocal8Bit(msg));
for(int j = 0;j < clientList.size();j++){
clientList[j]->write(msg);
}
}
}
}
cli:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server = new QTcpServer(this);
connect(server,&QTcpServer::newConnection,this,&Widget::newConnectionSlot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_startButton_clicked()
{
quint16 port = ui->portEdit->text().toUInt();
//监听客户端的连接请求
if(!server->listen(QHostAddress::Any,port)){
QMessageBox::information(this,"失败","监听失败");
return;
}else{
QMessageBox::information(this,"成功","服务器启动成功");
}
}
void Widget::newConnectionSlot()
{
//qDebug()<<"您有新的客户端发来请求";
QTcpSocket *s = server->nextPendingConnection();
clientList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::readyReadSlot);
}
void Widget::readyReadSlot()
{
for(int i = 0;i < clientList.size();i++){
//判断当前套接字是否有效连接
if(!clientList[i]->state()){
//将该套接字移除客户端容易
clientList.removeAt(i);
}
}
for(int i = 0;i < clientList.size();i++){
if(clientList[i]->bytesAvailable()){
//将该套接字的数据读取出来
QByteArray msg = clientList[i]->readAll();
ui->msgWidget->addItem(QString::fromLocal8Bit(msg));
for(int j = 0;j < clientList.size();j++){
clientList[j]->write(msg);
}
}
}
}
效果图: