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

简易网络聊天室服务端.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());
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,949评论 19 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 12,817评论 6 13
  • 参考:http://www.2cto.com/net/201611/569006.html TCP HTTP UD...
    F麦子阅读 3,081评论 0 14
  • 1、TCP状态linux查看tcp的状态命令:1)、netstat -nat 查看TCP各个状态的数量2)、lso...
    北辰青阅读 9,779评论 0 11
  • 离开学校快一个月了,期待的漫长假期并没有想象的轰轰烈烈。 练车黑了两个色号,不练车时整天在床上无所事事,我就这样的...
    污力阿娇i阅读 165评论 0 0

友情链接更多精彩内容