QT建立控制台项目,还是用最简单的c/s 模式.
client端:
#ifndef UDP_UDPclient_H
#define UDP_UDPclient_H
#include <work/QUdpSocket>
#include <QHostAddress>
#include <QThread>
#pragma once
class UDPclient: public QObject
{
Q_OBJECT
public:
void InitSocket();
private slots:
void Recv();
};
#endif
#include ""
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;
(udpSocket->pendingDatagramSize());
udpSocket->readDatagram((), ());
for (int i = 0; i < (); ++i)
{
printf( " %x",(i));
}
printf("\n");
}
}
函数解释:pendingDatagramSize 当有数据包读入时返回true.
resize 为datageam设置大小
pendingDatagramSize 返回udosocket第一个数据包的大小
readDatagram 读数据包
server端,顺便学****写下个多进程QThread:
#include <QtGui/QApplication>
#include ""
int main(int argc, char *argv[])
{
UDP_QT Server;
QCoreApplication a(argc, argv);
();
();//进程开始
return ();
}
#ifndef UDP_QT_H
QT UDP SOCKET编程 来自淘豆网www.taodocs.com转载请标明出处.