运用网络通信,实现简单聊天室
客户端主要代码
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, socket(new QTcpSocket(this))
{
ui->setupUi(this);
//初始化界面
ui->msgEdit->setEnabled(false);
ui->sendbtn->setEnabled(false);
ui->offbtn->setEnabled(false);
connect(socket,&QTcpSocket::connected,this,&Widget::connect_slots);
connect(socket,&QTcpSocket::readyRead,this,&Widget::read_slots);
connect(socket,&QTcpSocket::disconnected,this,&Widget::offend_slots);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_connectbtn_clicked()
{
QString ip= ui->ipEdit->text();
quint16 port=ui->portEdit->text().toUInt();//字符串转换为整型
//让客户端连接服务器
socket->connectToHost(ip,port);
}
void Widget::connect_slots()
{
userName = ui->usernameEdit->text();
QString msg = userName+":进入聊天室";
socket->write(msg.toLocal8Bit());
QMessageBox::information(this,"","连接成功");
ui->msgEdit->setEnabled(true);
ui->sendbtn->setEnabled(true);
ui->offbtn->setEnabled(true);
ui->usernameEdit->setEnabled(false);
ui->ipEdit->setEnabled(false);
ui->portEdit->setEnabled(false);
ui->connectbtn->setEnabled(false);
}
void Widget::read_slots()
{
QByteArray msg=socket->readAll();
QString mag=(QString::fromLocal8Bit(msg));
if(mag==msgsend){
QListWidgetItem *item = new QListWidgetItem(mag);
item->setTextAlignment(Qt::AlignRight);
ui->listWidget->addItem(item);
ui->sendbtn->setEnabled(true);
killTimer(id);
ui->msgEdit->clear();
}else{ ui->listWidget->addItem(mag);
}
}
void Widget::on_sendbtn_clicked()
{
msgsend=ui->msgEdit->text();
msgsend = userName + " :" +msgsend;
id=startTimer(500);
ui->sendbtn->setEnabled(false);
socket->write(msgsend.toLocal8Bit());
}
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId()==id)
{
ui->sendbtn->setEnabled(true);
killTimer(id);
}
}
void Widget::offend_slots()
{
ui->usernameEdit->setEnabled(true);
ui->ipEdit->setEnabled(true);
ui->portEdit->setEnabled(true);
ui->connectbtn->setEnabled(true);
ui->msgEdit->setEnabled(false);
ui->offbtn->setEnabled(false);
ui->sendbtn->setEnabled(false);
}
void Widget::on_offbtn_clicked()
{
QString msg =userName +":离开聊天室";
socket->write(msg.toLocal8Bit());
//断开连接
socket->disconnectFromHost();
}
实现效果