聊天室代码:
#include "cli.h"
#include "ui_cli.h"Cli::Cli(QWidget *parent): QWidget(parent), ui(new Ui::Cli)
{ui->setupUi(this);socket = new QTcpSocket(this);connect(socket,&QTcpSocket::connected,this,&Cli::connect_slot);//客户端与服务器连接成功后,如果服务器向客户端发来数据,客户端就会自动发送一个readyRead信号connect(socket,&QTcpSocket::readyRead,this,&Cli::readyRead_slot);connect(socket,&QTcpSocket::disconnected,this,&Cli::disconnect_slot);
}Cli::~Cli()
{delete ui;
}//连接服务器按钮对应的槽
void Cli::on_ConnectBtn_clicked()
{//获取UI界面的信息userName=ui->UserEdit->text();QString hostName = ui->IPEdit->text();quint16 port = ui->PortEdit->text().toUInt();qDebug() << "Connecting to host: " << hostName << " Port: " << port;//调用连接函数到主机//参数1:要连接的服务器主机地址//参数2:端口号//返回值:无socket->connectToHost(hostName,port);//如果连接服务器成功,该客户端回发送一个connected的信号//可以将信号连接到自定义的槽函数中处理相关逻辑//只连接一次 所有可以写在构造函数中
}void Cli::connect_slot()
{QMessageBox::information(this,"成功","连接服务器成功");QString msg = userName + ":进入聊天室";socket->write(msg.toLocal8Bit());
}void Cli::readyRead_slot()
{QByteArray msg = socket->readAll();//将数据展示在UI界面ui->MsgList->addItem(QString::fromLocal8Bit(msg));
}void Cli::on_SendBtn_clicked()
{QString m =ui->MsgEdit->text();QString msg = userName+":"+m;socket->write(msg.toLocal8Bit());ui->MsgEdit->clear();
}void Cli::on_DisBtn_clicked()
{QString msg=userName+":离开聊天室";socket->disconnectFromHost();//断开连接后 会向服务器发送disconnected信号
}void Cli::disconnect_slot()
{QMessageBox::information(this,"断开成功","断开成功");
}