QT 的UDP SOCKET编程

来源:互联网 发布:亚当斯密 知乎 编辑:程序博客网 时间:2024/06/06 18:33

QT建立控制台项目,还是用最简单的c/s 模式.

client端:
UDPclient.h
 

#ifndef UDP_UDPclient_H
#define UDP_UDPclient_H

#include <QtNetwork/QUdpSocket>
#include <QHostAddress>
#include <QThread>

#pragma once
 
class UDPclient: public QObject
{
  Q_OBJECT 
public:
 void InitSocket();
private slots:
    void Recv();
};
#endif

UDPclient.cpp

 

#include "UDPclient.h"

QUdpSocket  *udpSocket;   //套接字对象
void UDPclient::InitSocket()
{
  udpSocket = new QUdpSocket(this);
  udpSocket->bind(QHostAddress::Any,2002);
  connect(udpSocket, SIGNAL(readyRead()),
   this, SLOT(Recv()));
}
void UDPclient::Recv()
{
  while (udpSocket->hasPendingDatagrams())
 {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());                            
  for (int i = 0; i < datagram.size(); ++i)
  {
   printf( " %x",datagram.at(i));
  }
  printf("/n");
    }
}

函数解释:pendingDatagramSize  当有数据包读入时返回true.

         resize 为datageam设置大小

         pendingDatagramSize 返回udosocket第一个数据包的大小

         readDatagram 读数据包

 

server端,顺便学习写下个多进程QThread:

main.cpp

 

#include <QtGui/QApplication>
#include "UDP_QT.h"

int main(int argc, char *argv[])
{  
 UDP_QT Server;
 QCoreApplication a(argc, argv);
 Server.InitSocket();
 Server.start();//进程开始
    return a.exec();
}

UDP_QT.h
 

#ifndef UDP_QT_H
#define UDP_QT_H

#include <QtNetwork/QUdpSocket>
#include <QHostAddress>
#include <QThread>


#pragma once
 
class UDP_QT: public QThread
{

private:
    void Send();

public:
 void InitSocket();
 void run();
};
#endif

 

 

UDP_QT.cpp

 

#include "UDP_QT.h"
QUdpSocket  *udpSocket;   //套接字对象

char ToAddress[20]="10.144.123.237";

void UDP_QT::InitSocket()
{
 udpSocket = new QUdpSocket(this);
}
void UDP_QT::Send()
{
 char information[]="adg";

 while(1)
 {
  udpSocket->writeDatagram(information,QHostAddress(ToAddress),2002);
     printf("send datagram:");
   for (int i = 0; i < sizeof(information); ++i)
  {
   printf("%d",information[i]);
  }
  static int count=0;
  printf("/n%d",count++);
   sleep(1); //sleep函数要在进程下才能使用,它继承QThread
 }
}
void UDP_QT::run() //运行进程
{
  Send();
}


 以上仿照QT帮助写的.

原创粉丝点击