[Qt] 基于Tcp协议的聊天室实现(Chat Room 局域网通信)
時間:2016年12月11日
?
一、寫在前面:
? ? ? ? 平時做圖形學的東西多一些,雖然一直對網絡編程很感興趣,但是沒有什么機會去嘗試一下。最近正好趕上期末的課程實習,然后就參考Qt官方的 Network Programming References,寫了一個局域網群聊軟件,還算比較好看吧~ ,因為是自己的提交的作業,所以比較簡陋將就一下,主要功能有:
? ? ? ? (1) 用戶注冊與登錄
? ? ? ? (2) 多用戶加入聊天室聊天。
? ? ? ? (3) 找回密碼等服務功能。
?
二、在正文開始之前,先貼一下我的實現結果:
(1) 【客戶端】 ?聊天室聊天界面
? ? ? ?包含“用戶的基本信息”、“聊天窗口”、“當前在線用戶表”。截圖中有四個用戶同時在線。
? ? ? ? ? ?、
? ? ? ? ? ?
(2) 【服務器】?
? ? ? ? ? 負責管理用戶信息、轉發聊天消息等功能。截圖為上圖時刻的服務器狀態。
? ?
?
(3) 【客戶端】 ?用戶登錄
??? ?
?
三、【原理】 基于Qt實現Tcp協議的聊天室簡單Demo
1. 關于Tcp協議:
? ? ??TCP協議是一種面向連接的、可靠的、基于字節流的傳輸層通信協議。Qt對其提供了簡單的封裝,當然用windows API或Linux的<sys/socket.h>都能夠輕松實現。
? ? ? 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 <QMainWindow> #include <QTcpSocket> #include <QHostAddress>namespace Ui { class ClientWindow; }class ClientWindow : public QMainWindow {Q_OBJECTpublic: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()); // Exceptionui->lineEdit->clear(); }ClientWindow::~ClientWindow() {delete ui; }
(2) 服務器端程序:TcpServer
?
?
// 程序:TcpClient // 頭文件:serverWindow.h#ifndef SERVERWINDOW_H #define SERVERWINDOW_H#include <QMainWindow> #include <QTcpSocket> #include <QTcpServer>namespace Ui { class ServerWindow; }class ServerWindow : public QMainWindow {Q_OBJECTpublic:explicit ServerWindow(QWidget *parent = 0);~ServerWindow();QTcpServer* m_server;QList<QTcpSocket*> 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; i<m_sockets.size(); i++){m_sockets[i]->write(str.toStdString().data());} }ServerWindow::~ServerWindow() {delete ui; }?
?
?
總結
以上是生活随笔為你收集整理的[Qt] 基于Tcp协议的聊天室实现(Chat Room 局域网通信)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kali 工具系列【2】在kali li
- 下一篇: OpenLayers - 加载静态图片(