Qt學習 之 Socket通信


近期寫大作業用到Qt的Socket部分。網上關於這部分的資料都太過復雜,如今總結一下一些簡單的應用。有機會能夠給大家講講用Socket傳送文件的代碼。

這里主要解說怎樣實現TCP和UDP的簡單通信。

socket簡單介紹

在LINUX下進行網絡編程。我們能夠使用LINUX提供的統一的套接字接口。

可是這樣的方法牽涉到太多的結構體,比方IP地址,端口轉換等,不熟練的人往往easy犯這樣那樣的錯誤。QT中提供的SOCKET全然使用了類的封裝機制,使用戶不須要接觸底層的各種結構體操作。並且它採用QT本身的signal-slot機制。使編寫的程序更easy理解。

這是文檔

個人認為,QT的文檔除了缺少一些樣例,其它還是不錯的。

QT5中相比於QT4應該更新了一些socket的應用。QT4相比於QT3也更新了不少。並且還改了非常多的類名。大家在網上找資料的時候一定要注意。

UDP通信

UDP沒有特定的server端和client端,簡單來說就是向特定的ip發送報文,因此我把它分為發送端和接收端。

注意:在.pro文件里要加入QT += network。否則無法使用Qt的網絡功能。

發送端

#include <QtNetwork>
QUdpSocket *sender;
sender = new QUdpSocket(this);

QByteArray datagram = “hello world!”;

//UDP廣播
sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,6665);

//向特定IP發送
QHostAddress serverAddress = QHostAddress("10.21.11.66");
sender->writeDatagram(datagram.data(), datagram.size(),serverAddress, 6665);

/* writeDatagram函數原型,發送成功返回字節數,否則-1
qint64 writeDatagram(const char *data,qint64 size,const QHostAddress &address,quint16 port)
qint64 writeDatagram(const QByteArray &datagram,const QHostAddress &host,quint16 port)
*/

UDP接收端

#include <QtNetwork>
QUdpSocket *receiver;

//信號槽
private slots:  
    void readPendingDatagrams(); 

receiver = new QUdpSocket(this);
receiver->bind(QHostAddress::LocalHost, 6665);
connect(receiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));

void readPendingDatagrams()
 {
     while (receiver->hasPendingDatagrams()) {
         QByteArray datagram;
         datagram.resize(receiver->pendingDatagramSize());
         receiver->readDatagram(datagram.data(), datagram.size());
         //數據接收在datagram里
/* readDatagram 函數原型 qint64 readDatagram(char *data,qint64 maxSize,QHostAddress *address=0,quint16 *port=0) */
     }
 }

TCP通信

TCP的話要復雜點,必須先建立連接才干數據傳輸,分為server端和client端。

TCP client端

#include <QtNetwork>
QTcpSocket *client;
char *data="hello qt!";
client = new QTcpSocket(this);
client->connectToHost(QHostAddress("10.21.11.66"), 6665);
client->write(data);

TCP server端

#include <QtNetwork>
QTcpServer *server;
QTcpSocket *clientConnection;
server = new QTcpServer();
server->listen(QHostAddress::Any, 6665);
connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
void acceptConnection()
{
    clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
}
void readClient()
{
    QString str = clientConnection->readAll();
    //或者
    char buf[1024];
    clientConnection->read(buf,1024);
}

至於傳中文亂碼的問題,事實上能夠在前面的文章中解決。

也能夠看看這個


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM