Qt Socket简单通信

2013年03月12日 分类:学习笔记Linux嵌入式

最近要用到Qt的Socket部分,网上关于这部分的资料都比较复杂,我在这总结一下,把Socket的主要部分提取出来,实现TCP和UDP的简单通信。

1.UDP通信

UDP没有特定的server端和client端,简单来说就是向特定的ip发送报文,因此我把它分为发送端和接收端。 注意:在.pro文件中要添加QT += network,否则无法使用Qt的网络功能

1.1.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)
*/

1.2.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)
*/
     }
 }

2.TCP通信

TCP的话要复杂点,必须先建立连接才能传输数据,分为server端和client端。

2.1.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);

2.2.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);
}
作者:wuyuan 本文来自Wuyuan's Blog 转载请注明,谢谢! 文章地址: https://wuyuans.com/2013/03/qt-socket