Qt開發:TCP和UDP網路通訊
阿新 • • 發佈:2019-02-19
【原文】http://wuyuans.com/2013/03/qt-socket/
這篇文章簡潔清晰
TCP
客戶端
#include <QtNetwork>
QTcpSocket *client;
char *data="hello qt!";
client = new QTcpSocket(this);
client->connectToHost(QHostAddress("10.21.11.66"), 6665);
client->write(data);
服務端
#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); }
UDP
客戶端
#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) */
服務端
#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) */ } }
注意
- 只是簡單的收發功能,其中伺服器和客戶端收發的API是一樣的
- 可以獲取所連線的IP和port,未寫
- 可以繫結其他的訊號槽,比如disconnect,未寫
- udp傳送不一定要廣播,可以指定ip和埠
- 以上程式碼需要新增到h和cpp的合適位置