其实一般情况下我们都要考虑线程,先新建一个qt工程,取名udpclient,我一般喜欢用MainWindow,然后添加新文件,随意取名,例如thread,继承自QObiject
然后在.pro文件中加入以下两行代码
QT +=network
#用socket的话一定要加上,否则会报错
QMAKE_CXXFLAGS +=-std=c++0x
#这句话可以用一些c++的库
之后是thread的头文件
thread.h
#ifndef THREAD_H
#define THREAD_H
#include <QObject>
#include <QUdpSocket>
#include <QDebug>
#include <QThread>
extern QHostAddress addr;
extern quint16 port;
extern int shuju[];
class thread : public QObject
{
Q_OBJECT
public:
explicit thread(QObject *parent = 0);
QUdpSocket *mudpsocket;
~thread();
signals:
void sig_ok();
public slots:
void receiveDatagrams();
};
#endif // THREAD_H
thread.cpp
#include "thread.h"
thread::thread(QObject *parent) :
QObject(parent)
{
mudpsocket = new QUdpSocket(this);
mudpsocket->bind(QHostAddress("127.0.0.1"),1234);
}
thread::~thread()
{
delete mudpsocket;
}
void thread::receiveDatagrams()
{
while(1)
{
//接收数据
while(mudpsocket->hasPendingDatagrams())//当有数据来临时
{
int allDataLen = mudpsocket->pendingDatagramSize();//将套接字的长度赋给allDataLen
qDebug()<<"....alldatelen"<<allDataLen;
char* alldata = new char[allDataLen];
mudpsocket->readDatagram((char*)alldata,allDataLen,&addr,&port);//readDatagram
//函数读取套接字中长度为allDataLen的
//数据赋给类型是char*的数组,并且把目
//的IP和端口号也一并赋给addr和port.
qDebug()<<"addr"<<addr;
shuju[ssj] = *(unsigned char*)(alldata+ssj);//收数据
emit sig_ok();//这个信号可以触发mainwindow里的槽,看需求,因为我要用所以就加了,不需
//要的可以去掉
}
QThread::msleep(100);//如果while循环过快,那么cpu很容易跑满,
//然后程序就会挂掉,可以在while循环外加一个while(1),并加一个延时
}
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "thread.h"
extern QHostAddress addr;
extern quint16 port;
extern int shuju[];
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public:
thread *mythread;
QThread *thread1;
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp的代码就很简单了
#include "mainwindow.h"
#include "ui_mainwindow.h"
QHostAddress addr;//定义全局变量,在mainwindow.cpp中初始化,在mainwindow.h中加extern声明
//全局,其他文件要用直接在.h文件声明extern就可以
quint16 port;
int shuju[100]={};//一定要初始化内存大小,否则有可能会出现内存越界
QSettings *configIni;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mythread = new thread;
thread1 = new QThread(this);
mythread->moveToThread(thread1);
thread1->start();
connect(mythread->mudpsocket,SIGNAL(readyRead()),mythread,SLOT(receiveDatagrams()));
//当有数据写入套接字时,自动触发readyRead信号
}
MainWindow::~MainWindow()
{
delete ui;
}
接下来写发送端,新建一个工程,起名为udpserver
udpserver.cpp
#include "updserver.h"
#include <QUdpSocket>
updserver::updserver()
{
QUdpSocket send_socket;
char* alldata[2];
alldata[0]=1;
alldata[1]=2;
send_socket.writeDatagram((char*)alldata,allDataLen,QHostAddress("127.0.0.1"),1234);
}