服务器
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server=new QTcpServer(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
quint16 port=ui->lineEdit->text().toUInt();
if(!server->listen(QHostAddress::Any,port))
{
QMessageBox::critical(this,"错误","服务器启动失败");
return;
}else
{
QMessageBox::information(this,"成功","服务器启动成功");
}
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
QTcpSocket *s;
s=server->nextPendingConnection();
list.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_sloat);
}
void Widget::readyRead_sloat()
{
for(int i=0;i<list.count();i++)
{
if(!list[i]->state())
{
list.removeAt(i);
}
}
for(int i=0;i<list.count();i++)
{
if(list[i]->bytesAvailable())
{
QByteArray msg=list[i]->readAll();
ui->listWidget->addItem(QString::fromLocal8Bit(msg));
for(int j=0;j<list.count();j++)
{
list[j]->write(msg);
}
}
}
}
客户端
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);
connect(socket,&QTcpSocket::readyRead,this,&Widget::readtRead_slot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_lj_btn_clicked()
{
username=ui->name_edit->text();
quint16 port=ui->port_edit->text().toUInt();
QString ipname=ui->ip_edit->text();
socket->connectToHost(ipname,port);
}
void Widget::connected_slot()
{
QString s=username+"上线";
socket->write(s.toLocal8Bit());
QMessageBox::information(this,"成功","连接成功");
}
void Widget::readtRead_slot()
{
QByteArray s=socket->readAll();
ui->listWidget->addItem(QString::fromLocal8Bit(s));
}
void Widget::on_fs_btn_clicked()
{
QString s=username+":"+ui->xx_edit->text();
socket->write(s.toLocal8Bit());
ui->xx_edit->clear();
}
void Widget::on_dk_btn_clicked()
{
QString s=username+"退出聊天室";
socket->write(s.toLocal8Bit());
socket->disconnectFromHost();
QMessageBox::information(this,"退出","成功断开");
}