#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);
ui->send_2->setEnabled(false);
ui->textEdit->setEnabled(true);
}
Widget::~Widget()
{
delete ui;
}
//启动按钮对应的槽函数
void Widget::on_startBtn_clicked()
{
//设置服务器监听
quint16 port = ui->portEdit->text().toUInt();
if(server-> listen(QHostAddress::Any, port))
{
QMessageBox::information(this, "", "启动成功");
ui->startBtn->setText("关闭服务器");
}else
{
QMessageBox::critical(this, "", "监听失败");
this->close();
}
//将该信号连接到自定义的槽函数中
connect(server, &QTcpServer::newConnection, this, &Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
//使用nextPendingConnection()获取客户端套接字
QTcpSocket *s = server->nextPendingConnection();
//将客户端放入容器中
socketList.push_back(s);
//客户端发送readyRead信号,连接到对应的槽函数
connect(s, &QTcpSocket::readyRead, this, &Widget::readyRead_slot);
}
//readyRead信号对应的槽函数读取数据
void Widget::readyRead_slot()
{
//客户端实现代码
//将服务器发来的内容在ui上展示
ui->listWidget->addItem(QString::fromLocal8Bit(socket->readAll()));
//服务器实现代码
// //遍历删除
// for(int i = 0; i < socketList.count(); i++)//count 元素个数
// {
// 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界面上
// ui->listWidget->addItem(QString::fromLocal8Bit(msg));
// //将数据发给所有人
// for(int j = 0; j < socketList.count(); j++){
// socketList.at(j)->write(msg);
// }
// }
// }
}
//TCP客户端连接连接按钮实现
void Widget::on_send_clicked()
{
if(ui->send->text() == "连接服务器")
{
quint16 port = ui->portEdit->text().toUInt();
//设置客户端对象
socket->connectToHost(ui->ipEdit->text(),port);
//连接成功执行成功的槽函数
connect(socket, SIGNAL(connected()), this, SLOT(connected_slot()));//connect(socket,&QTcpSocket::connected,this,&Widget::connected_solt);
}else
{
//断开连接
ui->send->setText("连接服务器");
socket->disconnectFromHost();
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected_slot()));
}
}
//发送按钮实现
void Widget::on_send_2_clicked()
{
QString str = ui->textEdit->text();
//发送数据
int ret = this->socket->write(str.toLocal8Bit().data());
if(ret==-1)
{
QMessageBox::information(this,"promote","Fail in send");
}
else
{
QMessageBox::information(this,"promote","Successfully sent");
}
}
void Widget::connected_slot()
{
QMessageBox::information(this,"","连接成功");
ui->send->setText("断开服务器");
//连接成功读取服务器端执行对应槽函数
connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
ui->send_2->setEnabled(true);
ui->textEdit->setEnabled(true);
}
void Widget::disconnected_slot()
{
QMessageBox::information(this,"promote","Successful disconnected");
}
20240619
于 2024-06-19 22:18:45 首次发布