QT网络聊天室练习

服务器

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);
    connect(socket,&QTcpSocket::readyRead,this,&Widget::readRead_slot);
    connect(socket,&QTcpSocket::disconnected,this,&Widget::disconnected_slot);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_Connet_Btn_clicked()
{
    QString ip = ui->Ip_Edit->text();
    quint16 port = ui->Port_Edit->text().toInt();
    UserName = ui->User_Edit->text();
    if(ui->Connet_Btn->text()=="连接服务器")
    {
        socket->connectToHost(ip,port);
        ui->Connet_Btn->setText("断开服务器");
    }else
    {
        QString msg = UserName +":离开聊天室";
        socket->write(msg.toLocal8Bit());
        socket->disconnectFromHost();
        ui->Connet_Btn->setText("连接服务器");
    }

}

void Widget::on_Send_Btn_clicked()
{
    QString msg = UserName + ":" + ui->Msg_Edit->text();
    socket->write(msg.toLocal8Bit());
    ui->Msg_Edit->clear();
}

void Widget::connected_slot()
{
    QMessageBox::information(this,"Success","连接成功");
    QString msg = UserName + ": 进入聊天室";
    socket->write(msg.toLocal8Bit());
}

void Widget::readRead_slot()
{
    QByteArray msg = socket->readAll();
    ui->listWidget->addItem(QString::fromLocal8Bit(msg));
}

void Widget::disconnected_slot()
{
    QMessageBox::information(this,"","成功断开连接");
}

客户端

#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_OpenSer_clicked()
{
    quint16 port = ui->PortEdit->text().toUInt();
    if(server->listen(QHostAddress::Any,port))
    {
        QMessageBox::warning(this,"test","正在监听");
    }
    connect(server,&QTcpServer::newConnection,this,&Widget::newconnect_slot);
}

void Widget::newconnect_slot()
{
    QTcpSocket *s = server->nextPendingConnection();
    clientVector.push_back(s);
    connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}

void Widget::readyRead_slot()
{
    for(int i=0;istate()==0)
        {
            clientVector.removeAt(i);
        }
    }
    for(int i=0;ibytesAvailable() != 0)
        {
            QByteArray msg = clientVector[i]->readAll();
            ui->MsgWidget->addItem(QString::fromLocal8Bit(msg));
            for(int j=0;jwrite(msg);
            }
        }
    }
}

结果

QT网络聊天室练习_第1张图片

 

你可能感兴趣的:(qt,网络,命令模式)