#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);socket = new QTcpSocket(this);//如果连接服务器成功,该客户端就会发射一个connected的信号。//我们可以将信号连接到自定义的槽函数中处理相关逻辑//由于该链接只需连接一次,所以卸载构造函数中即可connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);//客户端与服务器连接后,如果服务器想客户端发来数据,那么该客户端就会自动发送一个readRead信号//我们可以将该信号连接到自定义的槽函数中处理相关逻辑connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);connect(socket,&QTcpSocket::disconnected,this,&Widget::disconnected_slot);
}Widget::~Widget()
{delete ui;
}void Widget::on_connectBtn_clicked()
{//获取ui界面的信息userName = ui -> usernameEdit -> text();QString hostName = ui -> ipEdit -> text();quint16 port = ui -> portEdit ->text().toUInt();//调用函数连接到主机socket -> connectToHost(hostName,port);ui ->ipEdit -> setEnabled(false);ui ->portEdit -> setEnabled(false);ui ->connectBtn -> setEnabled(false);ui ->usernameEdit -> setEnabled(false);
}void Widget::connected_slot(){QMessageBox::information(this,"成功","连接服务器成功");QString msg = userName +"进入聊天室";socket -> write(msg.toLocal8Bit());
}void Widget::readyRead_slot(){//读取该客户端信号对应槽函数的实现QByteArray msg = socket ->readAll();ui -> msgList -> addItem(QString::fromLocal8Bit(msg));}void Widget::on_sendBtn_clicked()
{QString m = ui ->msgEdit ->text();QString msg = userName + ":"+m;socket -> write(msg.toLocal8Bit());ui -> msgEdit -> clear();}//断开服务器按钮对应的槽函数
void Widget::on_disConnectBtn_clicked()
{QString msg = userName + ":离开聊天室";socket -> write(msg.toLocal8Bit());//调用成员函数disconnectFromHost//功能:断开客户端与服务器的连接socket -> disconnectFromHost();//当客户端与服务器断开连接后,该客户端就会发射一个disconnected的信号//我们可以将该信号与自定义的槽函数连接ui ->ipEdit -> setEnabled(true);ui ->portEdit -> setEnabled(true);ui ->connectBtn -> setEnabled(true);ui ->usernameEdit -> setEnabled(true);
}void Widget::disconnected_slot(){QMessageBox::information(this,"退出","断开成功");
}