QT学习:基于TCP/IP的简易群聊系统

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40011728/article/details/77924196

查阅一些资料,我自己试着写了一个简单的聊天系统。
简易网络聊天室服务端.PNG
简易网络聊天室客户端.PNG

一、服务端

(一)创建套接字进行监听

    //创建套接字 socket()
    server = new QTcpServer(this);

    //监听,端口号:9999   bind(...), listen()
    bool isOk = server->listen(QHostAddress::Any,9999);

    //监听失败
    if(false == isOk)
    {
        QMessageBox::warning(this,"监听","监听失败");
        return;
    }

    //当有客户端链接时,触发信号:newConnection()
    connect(server,SIGNAL(newConnection()),this,SLOT(newClient()));

(二)连接客户端

void Server::newClient()
{
    QTcpSocket *client;

    //取出链接套接字   accept()
    client = server->nextPendingConnection();

    connect(client,SIGNAL(readyRead()),this,SLOT(tcpRead()));
    connect(client,SIGNAL(disconnected()),this,SLOT(disClient()));
    clients.push_back(client);
}

(三)读取信息并群发

void Server::tcpRead()
{
    //哪一个QTcpSocketc对象可读就会发出readyRead()信号,通过信号的发出者找到相应的对象
    QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString str = QHostAddress(client->peerAddress().toIPv4Address()).toString() + ": " + time;
    ui->MessageBrowser->append(str);
    ui->MessageBrowser->append(client->readAll());

    //群发
    QList<QTcpSocket *>::iterator it;
    for(it = clients.begin();it != clients.end();it++)
        (*it)->write(str.toUtf8());
}

(四)退出客户端

void Server::disClient()
{
    QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());
    clients.removeOne(client);
}

二、客户端

(一)连接服务器

Client::Client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);

    tcp = new QTcpSocket(this);
    tcp->connectToHost("127.0.0.1",9999);
    if(!tcp->waitForConnected(3000))
    {
        QMessageBox::warning(this,"错误","连接失败");
        return;
    }

    connect(tcp,SIGNAL(readyRead()),this,SLOT(tcpRead()));
    connect(ui->sendpushButton,SIGNAL(clicked(bool)),this,SLOT(tcpSend()));
}

(二)读取信息

void Client::tcpRead()
{
    QString str;

    str = tcp->readAll();
    ui->textBrowser->append(str);
    ui->textBrowser->moveCursor(QTextCursor::End);
    ui->textBrowser->append(ui->sendlineEdit->text());
}

(三)发送信息

void Client::tcpSend()
{
    QString str = ui->sendlineEdit->text();
    tcp->write(str.toUtf8());
}

该聊天系统能实现群聊功能,即一个客户端向服务器发送信息,服务器接受信息之后将接受的信息发给所有与服务器相连的客户端。

展开阅读全文

没有更多推荐了,返回首页