Qtソケット簡単通信

27916 ワード

最近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. }
:wuyuan Wuyuan's Blog , ! : http://wuyuans.com/2013/03/qt-socket/