Qt Socket通信(UDP&TCP)

来源:互联网 发布:mac ps怎么破解 编辑:程序博客网 时间:2024/04/28 16:40

socket简介

在Linux下进行网络编程,我们可以使用LINUX提供的统一的套接字接口。但是这种方法牵涉到太多的结构体,比如IP地址,端口转换等,不熟练的人往往容易犯这样那样的错误。QT中提供的SOCKET完全使用了类的封装机制,使用户不需要接触底层的各种结构体操作。而且它采用QT本身的signal-slot机制,使编写的程序更容易理解。

这是文档。个人觉得,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函数原型,发送成功返回字节数,否则-1qint64 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);}

原文:http://blog.csdn.net/u013007900/article/details/50411796

0 0