QUdpSocket简单的使用(局域网内发送给所有客户端消息与接收)
来源:互联网 发布:淘宝网买短款真丝旗袍 编辑:程序博客网 时间:2024/05/22 13:09
先看一下效果:
(程序服务端在不断发送消息,接收端每隔2秒接收一次消息)
服务端和客户端都用到一个公共类:
UDPServerAndClient.h:
#ifndef UDPSERVERANDCLIENT_H
#define UDPSERVERANDCLIENT_H
#include <QObject>
#include <QUdpSocket>
#include <QTimer>
class UDPServerAndClient : public QObject
{
Q_OBJECT
public:
explicit UDPServerAndClient(QObject *parent = 0);
void setServerInit();
void setClientInit();
private slots:
void onServerSendBroadcast();
void onPendingDatagrams();
private:
QUdpSocket udpSocketServer;
QUdpSocket udpSocketClient;
QTimer timer;
};
#endif // UDPSERVERANDCLIENT_H
UDPServerAndClient.cpp:
#include "udpserverandclient.h"
#include <QHostInfo>
#include <QDataStream>
#include <QDateTime>
UDPServerAndClient::UDPServerAndClient(QObject *parent) : QObject(parent)
{
}
void UDPServerAndClient::setServerInit()
{
connect(&timer, SIGNAL(timeout()), this, SLOT(onServerSendBroadcast())); //定时发送
timer.start(2000);
}
void UDPServerAndClient::setClientInit()
{
udpSocketClient.bind(13999); //建立监听
connect(&udpSocketClient, SIGNAL(readyRead()), this, SLOT(onPendingDatagrams())); //接收准备
}
void UDPServerAndClient::onServerSendBroadcast()
{
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_6);
out << QDateTime::currentDateTime() << QHostInfo::fromName(QHostInfo::localHostName()).addresses().last().toString();
//发送主机可以用QHostAddress("127.0.0.1")替换
udpSocketServer.writeDatagram(datagram, QHostAddress::Broadcast, 13999); // UDP 发送数据
}
void UDPServerAndClient::onPendingDatagrams()
{
QByteArray datagram;
do{
datagram.resize(udpSocketClient.pendingDatagramSize());
udpSocketClient.readDatagram(datagram.data(), datagram.size()); //接收数据
} while( udpSocketClient.hasPendingDatagrams() );
QDateTime dateTime;
QString lastIP;
QDataStream in(&datagram, QIODevice::ReadOnly);
in.setVersion(QDataStream::Qt_5_6);
in >> dateTime >> lastIP;
qDebug() <<"dateTime.date().toString():" << dateTime.date().toString()
<<"ip:" << lastIP;
}
- QUdpSocket简单的使用(局域网内发送给所有客户端消息与接收)
- 给局域网中所有的计算机发送消息
- Scala:简单使用Actor的消息发送与接收求和
- Android中基于ServerSocket的实际使用与简单介绍(内附一个PC端群控多台手机的消息发送和接收Demo)
- 局域网聊天工具(多线程),支持客户端与客户端间通信,服务器负责信息的接收与发送
- 局域网聊天工具(多线程),支持客户端与客户端间通信,服务器负责信息的接收与发送(client)
- AsyncSocket(简单的实现与服务器的发送消息,接收消息)
- 消息队列(一)——消息的简单发送与接收
- RabbitMQ之最简单的消息的发送与接收
- 超简单的 andirod 消息发送与接收
- 在Python中发送广播消息并接收所有客户端响应的小脚本
- 使用RabbitMQ简单发送接收消息
- spring activeMQ 整合(一): 一个简单的demo,测试消息的发送与接收
- ActiveMQ使用笔记(三)ActiveMQ消息发送与接收
- ActiveMQ使用笔记(三)ActiveMQ消息发送与接收
- 简单的unity 客户端与服务端互相发送消息
- Webservice的wsdl文件解析与Soap消息的发送、接收(不生成java客户端代码)
- 内网客户端使用UDP接收外网消息
- 贪婪算法、递归计算、动态规划背包问题
- php面向对象中static静态属性和静态方法的调用
- 计算机操作系统之概述(一)
- ffmpeg 入门
- HTTP协议详解
- QUdpSocket简单的使用(局域网内发送给所有客户端消息与接收)
- 第15周项目1-验证算法(3)希尔排序
- 通过python-ldap处理ldap服务器
- 精度丢失
- SSH 整合 -------一:准备工作
- eq(equal)等于,ne neq(not equal)不等于,gt(greater than)大于 (smarty)
- w32dasm手动汇编教程:
- vim 问题
- mybatis的in查询