[Qt] 基于Tcp协议的聊天室实现(Chat Room 局域网通信)

您所在的位置:网站首页 qq里的聊天室在哪 [Qt] 基于Tcp协议的聊天室实现(Chat Room 局域网通信)

[Qt] 基于Tcp协议的聊天室实现(Chat Room 局域网通信)

2024-07-07 15:27| 来源: 网络整理| 查看: 265

时间:2016年12月11日

 

一、写在前面:

        平时做图形学的东西多一些,虽然一直对网络编程很感兴趣,但是没有什么机会去尝试一下。最近正好赶上期末的课程实习,然后就参考Qt官方的 Network Programming References,写了一个局域网群聊软件,还算比较好看吧~ ,因为是自己的提交的作业,所以比较简陋将就一下,主要功能有:

        (1) 用户注册与登录

        (2) 多用户加入聊天室聊天。

        (3) 找回密码等服务功能。

 

二、在正文开始之前,先贴一下我的实现结果:

(1) 【客户端】  聊天室聊天界面

       包含“用户的基本信息”、“聊天窗口”、“当前在线用户表”。截图中有四个用户同时在线。

           

           

(2) 【服务器】 

          负责管理用户信息、转发聊天消息等功能。截图为上图时刻的服务器状态。

   

 

(3) 【客户端】  用户登录

     

 

三、【原理】 基于Qt实现Tcp协议的聊天室简单Demo 1. 关于Tcp协议:

      TCP协议是一种面向连接的、可靠的、基于字节流的传输层通信协议。Qt对其提供了简单的封装,当然用windows API或Linux的都能够轻松实现。

      TCP协议被称为面向连接的通信协议。原因是TCP协议的传输依赖于TCP连接。一个TCP连接,由两个套接字(socket)组成,分别位于数据传输的两端(在这里为客户端、服务器),字节流数据通过Tcp连接发送一对一消息。

2. 聊天室的通信流程:

    首先,启动一个服务器(Server),并使其监听(listen)服务器端的某个端口(port)。

    当Server收到某个客户端的socket发出的“建立连接”请求时,Server便在本地创建一个客户端socket的本地代理(也是一个socket),这样一个TCP连接便创建成功。 当然,服务器可以通过这个本地代理(socket)向服务器发送消息,而客户端也可以通过自己的socket与服务器方的代理socket发送消息。

    如果允许多个客户端连接到Server,那么可以用一个链表管理所有Server端的socket。

    我画了一个上述过程的流程图,如下:

3. Qt中的Tcp通信

       在Qt中,套接字由QTcpSocket支持,服务器由QTcpServer支持。关于这些类的具体信息可以在Qt的官方帮助文档(Qt Assistance)中查询到。

       在使用Qt的Network模块之前,先需要连接Qt的网络库文件。可在pro文件中,添加如下代码实现:

                  QT    += network

【3.1】QTcpServer的主要函数:

   boolQTcpServer::listen(const QHostAddress& address = QHostAddress::Any, quint16port = 0);          

      [Qt Assistance] Tells the server to listen for incoming connections on address and port. If port is 0, a port is chosen automatically. If address is QHostAddress::Any, the server will listen on all network interfaces.Returns true on success; otherwise returns false.

     告诉server他要监听来自哪里的连接和端口。如果address为QHostAddress::Any,server将会监听所有网络的连接请求,端口可以取没有被占用的任意端口号(如:19999)

   QTcpSocket* QTcpServer::nextPendingConnection()                            

    [Qt Assistance] Returns the next pending connection as a connected QTcpSocket object.

   返回服务器下一个已申请建立连接,但还未处理的socket。

【3.2】QTcpSocket的主要函数:

     voidQSocket::connectToHost(const QHostAddress & address, quint16 port, OpenMode openMode = ReadWrite)

     [Qt Assistance] Attempts to make a connection to address on port.

   尝试连接到IP地址为address,端口号为port的服务器。

     voidQAbstractSocket::abort()

     [Qt Assistance]  Aborts the current connection and resets the socket. 

     中断当前连接,并重置socket。

     读写操作:QTcpSocket::write(const char*)、QTcpSocket::writeAll(const char*)

 

4. 一个基于TCP协议的局域网聊天室的简单demo的具体代码和下载连接:

demo程序下载连接:  http://download.csdn.net/detail/mahabharata_/9877757

demo程序功能简介:该示例包含TcpClient和TcpServer两个程序。TcpClient为通信客户端,可以同时开启多个,TcpServer为服务器,用于实现消息的中继和转发。

demo程序演示图:

demo程序的主干代码:

(1) 客户端程序 TcpClient

 

// 程序:TcpClient // 头文件:clientWindow.h #ifndef CLIENTWINDOW_H #define CLIENTWINDOW_H #include #include #include namespace Ui { class ClientWindow; } class ClientWindow : public QMainWindow { Q_OBJECT public: explicit ClientWindow(QWidget *parent = 0); ~ClientWindow(); QTcpSocket* m_socket; // 客户端套接字 void connectToServer(); // 连接到服务器 private slots: void slot_readMessage(); // 处理接收服务器方发送的消息 void slot_btnSendMsg(); // 点击发送按钮后,后发送消息 private: Ui::ClientWindow *ui; }; #endif // CLIENTWINDOW_H

 

// 程序:TcpClient // 源文件:clientWindow.cpp #include "clientwindow.h" #include "ui_clientwindow.h" ClientWindow::ClientWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::ClientWindow) { ui->setupUi(this); connectToServer(); // do other things } void ClientWindow::connectToServer() { m_socket = new QTcpSocket(this); //连接到服务器 // 尝试连接到IP为"127.0.0.1" & 端口号为19999服务器 // 如果想要实现局域网通信, 只需将第一个IP地址设置为“服务器”所在主机的IP地址即可 // 如 m_socket->connectToHost("170.29.19.65", 19999); m_socket->connectToHost(QHostAddress::LocalHost, 9999); connect(m_socket,SIGNAL(readyRead()),this,SLOT(slot_readMessage())); // 告诉socket, 要用slot_readMessage()去处理接收的消息. connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(slot_btnSendMsg())); } void ClientWindow::slot_readMessage() // 只会在socket接收到server消息时调用 { QString str = m_socket->readAll().data(); ui->textBrowser->setText(ui->textBrowser->toPlainText() + "\n" + str); } void ClientWindow::slot_btnSendMsg() { QString str = ui->lineEdit->text(); m_socket->write(str.toStdString().data()); // Exception ui->lineEdit->clear(); } ClientWindow::~ClientWindow() { delete ui; }

(2) 服务器端程序:TcpServer

 

 

// 程序:TcpClient // 头文件:serverWindow.h #ifndef SERVERWINDOW_H #define SERVERWINDOW_H #include #include #include namespace Ui { class ServerWindow; } class ServerWindow : public QMainWindow { Q_OBJECT public: explicit ServerWindow(QWidget *parent = 0); ~ServerWindow(); QTcpServer* m_server; QList m_sockets; // 连接到server的所有客户. 链表方式, 在服务器端的一个备份(客户端的socket) void startServer(); // 启动一个server public slots: void slot_newConnection(); // 对应客户端的 connectToHost(); void slot_readMessage(); // 每一个socket绑定 private: Ui::ServerWindow *ui; }; #endif // SERVERWINDOW_H

 

// 程序:TcpClient // 源文件:serverWindow.cpp #include "serverwindow.h" #include "ui_serverwindow.h" ServerWindow::ServerWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::ServerWindow) { ui->setupUi(this); startServer(); } void ServerWindow::startServer() { m_server = new QTcpServer(this); m_server->listen(QHostAddress::Any, 19999); connect(m_server,SIGNAL(newConnection()),this,SLOT(slot_newConnection())); // } void ServerWindow::slot_newConnection() { // 把新加入的socket放入链表中 QTcpSocket* socket = m_server->nextPendingConnection(); m_sockets.push_back(socket); connect(socket,SIGNAL(readyRead()),this,SLOT(slot_readMessage())); } // 每一个socket处理收到消息的函数 void ServerWindow::slot_readMessage() { QTcpSocket* socket = (QTcpSocket*)QObject::sender(); // 获得是哪个socket收到了消息 QString str = socket->readAll().data(); for(int i=0; iwrite(str.toStdString().data()); } } ServerWindow::~ServerWindow() { delete ui; }

 

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3