打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
【2011.03.17】QT 的UDP SOCKET编程
 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();
}


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Qt之UDP的网络广播例子
Qt的Udp编程总结
Qt学习 之 Socket通信(世界上最简单的例子了)
Implementing Multicast Sockets in C#
Qt学习之路
高性能异步Socket服务器(UDP)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服