首页 > 其他 > 详细

简单Qt网络通信

时间:2014-11-16 23:02:02      阅读:572      评论:0      收藏:0      [点我收藏+]

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

1.UDP通信

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

1.1.UDP发送端

 

 1 #include <QtNetwork>
 2 QUdpSocket *sender;
 3 sender = new QUdpSocket(this);
 4 QByteArray datagram = “hello world!”;
 5 //UDP广播
 6 sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,6665);
 7 //向特定IP发送
 8 QHostAddress serverAddress = QHostAddress("10.21.11.66");
 9 sender->writeDatagram(datagram.data(), datagram.size(),serverAddress, 6665);
10 /* writeDatagram函数原型,发送成功返回字节数,否则-1
11 qint64 writeDatagram(const char *data,qint64 size,const QHostAddress &address,quint16 port)
12 qint64 writeDatagram(const QByteArray &datagram,const QHostAddress &host,quint16 port)
13 */

 

 

1.2.UDP接收端

 1 #include <QtNetwork>
 2 QUdpSocket *receiver;
 3 //信号槽
 4 private slots:
 5 void readPendingDatagrams();
 6 receiver = new QUdpSocket(this);
 7 receiver->bind(QHostAddress::LocalHost, 6665);
 8 connect(receiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));
 9 void readPendingDatagrams()
10 {
11 while (receiver->hasPendingDatagrams()) {
12 QByteArray datagram;
13 datagram.resize(receiver->pendingDatagramSize());
14 receiver->readDatagram(datagram.data(), datagram.size());
15 //数据接收在datagram里
16 /* readDatagram 函数原型
17 qint64 readDatagram(char *data,qint64 maxSize,QHostAddress *address=0,quint16 *port=0)
18 */
19 }
20 }

 

2.TCP通信

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

2.1.TCP client端

 

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

 

2.2.TCP server端

 1 #include <QtNetwork>
 2 QTcpServer *server;
 3 QTcpSocket *clientConnection;
 4 server = new QTcpServer();
 5 server->listen(QHostAddress::Any, 6665);
 6 connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
 7 void acceptConnection()
 8 {
 9 clientConnection = server->nextPendingConnection();
10 connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
11 }
12 void readClient()
13 {
14 QString str = clientConnection->readAll();
15 //或者
16 char buf[1024];
17 clientConnection->read(buf,1024);
18 }

 

简单Qt网络通信

原文:http://www.cnblogs.com/suanec/p/4102555.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!