時間: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_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 <QMainWindow>
#include <QTcpSocket>
#include <QTcpServer>
namespace Ui {
class ServerWindow;
}
class ServerWindow : public QMainWindow
{
Q_OBJECT
public:
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;
}