完善网络聊天室客户端实现
工程文件
QT += core gui network
头文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpSocket>
#include<QMessageBox>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_connect_clicked();void on_send_clicked();void on_cout_clicked();public slots://手动连接的槽函数声明void cslot();void rslot();void outslot();
private:Ui::Widget *ui;//实例化QTcpSocket *socket;QString uname;
};
#endif // WIDGET_H
源文件
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);socket=new QTcpSocket(this);//不可用功能ui->msgl->setEnabled(false);ui->send->setEnabled(false);ui->cout->setEnabled(false);//基于qt5的友好手动连接connect(socket,&QTcpSocket::connected,this,&Widget::cslot);connect(socket,&QTcpSocket::readyRead,this,&Widget::rslot);connect(socket,&QTcpSocket::disconnected,this,&Widget::outslot);}
Widget::~Widget()
{delete ui;
}
//连接按钮
void Widget::on_connect_clicked()
{QString ip=ui->ipl->text();quint16 port=ui->portl->text().toUInt();socket->connectToHost(ip,port);
}
//connected()槽函数
void Widget::cslot()
{QMessageBox::information(this,"","连接服务器成功");uname=ui->namel->text();QString msg=uname+":进入聊天室";socket->write(msg.toLocal8Bit());//可用功能ui->msgl->setEnabled(true);ui->send->setEnabled(true);ui->cout->setEnabled(true);//不可用功能ui->namel->setEnabled(false);ui->ipl->setEnabled(false);ui->portl->setEnabled(false);ui->connect->setEnabled(false);
}//readyRead()信号槽函数
void Widget::rslot()
{QByteArray msg=socket->readAll();ui->list->addItem(QString::fromLocal8Bit(msg));}
//发送按钮
void Widget::on_send_clicked()
{QString msg=uname+": "+ui->msgl->text();socket->write(msg.toLocal8Bit());ui->msgl->clear();
}//断开连接按钮
void Widget::on_cout_clicked()
{QString msg=uname+":离开聊天室";socket->write(msg.toLocal8Bit());socket->disconnectFromHost();
}
//disconnected()槽函数
void Widget::outslot()
{QMessageBox::information(this,"","断开连接");//不可用功能ui->msgl->setEnabled(false);ui->send->setEnabled(false);ui->cout->setEnabled(false);//可用功能ui->namel->setEnabled(true);ui->ipl->setEnabled(true);ui->portl->setEnabled(true);ui->connect->setEnabled(true);
}