本文整理汇总了C++中QUdpSocket类的典型用法代码示例。如果您正苦于以下问题:C++ QUdpSocket类的具体用法?C++ QUdpSocket怎么用?C++ QUdpSocket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QUdpSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: QUdpSocket
void FetchThread::process(QString phost)
{
QUdpSocket *udpSocket ;
udpSocket= new QUdpSocket(0);
udpSocket->bind(QHostAddress::LocalHost, 9999);
udpSocket->waitForConnected(250);
QTcpSocket socket;
socket.connectToHost("localhost", 4949);
socket.waitForConnected(500);
while (socket.waitForReadyRead(250));
QString t_hello = socket.readAll();
qDebug() << "READ: " << t_hello;
socket.write(QString("list\n").toStdString().c_str() );
while (socket.waitForReadyRead(250));
QString buf1 = socket.readAll();
qDebug() << "READ: " << buf1;
QStringList list_probe = buf1.split(QRegExp("\\s+"));
for (int z=0; z< list_probe.size(); z++)
{
QString probe=list_probe.at(z);
QString cmd = QString("fetch ").append(probe).append("\n");
qDebug() << "cmd : " << cmd;
socket.write(cmd.toStdString().c_str() );
while (socket.waitForReadyRead(250));
QString buf2 = socket.readAll();
qDebug() << "Rep fetch :" << buf2 << "\n";
QRegularExpression re("(\\w+).(\\w+) ([0-9.]+)\\n");
QRegularExpressionMatchIterator i = re.globalMatch(buf2);
re.setPatternOptions(QRegularExpression::MultilineOption);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
QString s_metric = match.captured(1);
QString s_value = match.captured(3);
QString s_mtr = "monit2influxdb,metric="+probe + "_" + s_metric + ",host=" + phost+ " value=" + s_value + " " + QString::number(1000000* QDateTime::currentMSecsSinceEpoch());
qDebug() << "metric: " << s_mtr.toLower();
udpSocket->writeDatagram(s_mtr.toStdString().c_str(), QHostAddress::LocalHost, 9999);
}
udpSocket->close();
}
}
示例2: qDebug
void MainWindow::controlMessageReceived() {
qDebug() << "message received";
QUdpSocket* udpSocket = qobject_cast<QUdpSocket*>(sender());
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
if (datagram=="left") {
drone->moveLeft();
} else if (datagram== "right") {
drone->moveRight();
} else if (datagram=="stayx" && datagram=="stayy"){
drone->stay();
} else if (datagram=="up") {
drone->higher();
} else if (datagram=="down") {
drone->lower();
} else {
qDebug() << "invalid command received";
}
}
}
示例3: SendNetworkPackets
void SendNetworkPackets(unsigned int i, unsigned int j, unsigned int k) { //sends desired data over UDP to the robot. I used it to send the # of squares and the ms required to render each frame. (It uses the time data to know when to read for UDP packets and hence the for loop iteration essentially stands for the # of frames it wants to read from the odroid.
static QUdpSocket udpSocket; //create socket
QByteArray datagram = QByteArray::number(i) + " " + QByteArray::number(j) + " " + QByteArray::number(k) + " "; //create data stream
udpSocket.writeDatagram(datagram.data(), datagram.size(), QHostAddress(QstringTargetIPAddress), TargetPortNumber); //send that data stream over UDP to the TargetIpAddress with the given TargetPortNumber
}
示例4: Client
void TestClient::testSendKeyInputPacket(){
Client* client = new Client(NULL);
QUdpSocket* socket = new QUdpSocket();
socket->bind(INCOMING_PORT);
client->setDirection(1);
client->setIsJumping(false);
client->setIsLaunching(true);
client->sendDatagram(KEY_INPUT_PACKET);
QHostAddress *address = NULL;
quint16 *port = NULL;
QByteArray *datagram = new QByteArray(socket->pendingDatagramSize(), (char) 0);
socket->readDatagram(datagram->data(), datagram->size(), address, port);
QCOMPARE(datagram->at(0), KEY_INPUT_PACKET);
QCOMPARE((int)datagram->at(1), -1);
QCOMPARE((int)datagram->at(2), 1);
QCOMPARE((bool)datagram->at(3), false);
QCOMPARE((bool)datagram->at(4), true);
delete socket;
}
示例5: next
// Called whenever there is data available on the device.
void SignalChunker::next(QIODevice* device)
{
// Get a pointer to the UDP socket.
QUdpSocket* udpSocket = static_cast<QUdpSocket*>(device);
_bytesRead = 0;
// Get writable buffer space for the chunk.
WritableData writableData = getDataStorage(_chunkSize);
if (writableData.isValid()) {
// Get pointer to start of writable memory.
char* ptr = (char*) (writableData.ptr());
// Read datagrams for chunk from the UDP socket.
while (isActive() && _bytesRead < _chunkSize) {
// Read the datagram, but avoid using pendingDatagramSize().
if (!udpSocket->hasPendingDatagrams()) {
// MUST WAIT for the next datagram.
udpSocket->waitForReadyRead(100);
continue;
}
qint64 maxlen = _chunkSize - _bytesRead;
qint64 length = udpSocket->readDatagram(ptr + _bytesRead, maxlen);
if (length > 0)
_bytesRead += length;
}
}
// Must discard the datagram if there is no available space.
else {
udpSocket->readDatagram(0, 0);
}
}
示例6: processPendingDatagrams
void ICServer::processPendingDatagrams()
{
QByteArray datagram;
QUdpSocket *socket = isRunning ? udpSocket : testUdpSocket;
do {
QHostAddress *address = new QHostAddress;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size(), address);
ICMessageHandler *messageHandler = new ICMessageHandler(this);
connect(messageHandler, SIGNAL(connectionOffer(QString)), this, SLOT(processSidCollision(QString)));
connect(messageHandler, SIGNAL(serverDiscovery(QHostAddress,QString)), this, SLOT(processDiscovery(QHostAddress,QString)));
connect(messageHandler, SIGNAL(questionRequest(QHostAddress)), this, SLOT(processRequest(QHostAddress)));
connect(messageHandler, SIGNAL(answerReady(ICAnswer,QString)), this, SLOT(processAnswer(ICAnswer,QString)));
ICMessageProcessor *processor = new ICMessageProcessor(messageHandler, *address, datagram);
QThreadPool::globalInstance()->start(processor);
qDebug()<< "[1] Received from " << *address << datagram;
delete address;
} while (socket->hasPendingDatagrams());
}
示例7: hasDmx
void QDmxE131Controler::readDatagram()
{
if(sender())
{
QUdpSocket* socket = qobject_cast<QUdpSocket*>(sender());
if(socket)
{
while(socket->hasPendingDatagrams())
{
QNetworkDatagram datagram = socket->receiveDatagram();
if(datagram.senderAddress().isInSubnet(_address, _entry.prefixLength()))
{
QByteArray rawData = datagram.data();
if(_packetizer->checkPacket(rawData))
{
QByteArray dmx;
quint32 u;
_packetizer->fillDMXdata(rawData, dmx, u);
u--;
if(_listenedUniverse.contains(u))
emit hasDmx(u, dmx);
}
}
}
}
}
}
示例8: onStunReadyRead
void StunClient::onStunReadyRead()
{
QUdpSocket *sock = (QUdpSocket*)(sender());
qDebug()<<""<<sock;
u08bits rbuf[STUN_BUFFER_SIZE];
while (sock->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(sock->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
sock->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
{
m_sending_udp = false;
m_sending_timer->stop();
}
qDebug()<<"read: "<<sender<<senderPort<<datagram.length()<<datagram.toHex().left(20)<<"...";
for (int i = 0; i < datagram.length(); i ++) {
char c = datagram.at(i);
fprintf(stderr, "%c", isprint(c) ? c : '.');
if (i > 375) break;
}
fprintf(stderr, " ...]\n");
this->processResponse(datagram, QString("%1:%2").arg(sender.toString()).arg(senderPort));
// processTheDatagram(datagram);
}
}
示例9: run
void NewRefereeModule::run() {
QUdpSocket socket;
if (!socket.bind(ProtobufRefereePort, QUdpSocket::ShareAddress)) {
throw runtime_error("Can't bind to shared referee port");
}
multicast_add(&socket, RefereeAddress);
_packets.reserve(4);
_running = true;
while (_running) {
if (!_useExternalRef) continue;
char buf[65536];
if (!socket.waitForReadyRead(500)) {
continue;
}
QHostAddress host;
quint16 port = 0;
qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &port);
if (size < 1) {
fprintf(stderr, "NewRefereeModule: %s/n",
(const char*)socket.errorString().toLatin1());
::usleep(100000);
continue;
}
NewRefereePacket* packet = new NewRefereePacket;
packet->receivedTime = RJ::timestamp();
this->received_time = packet->receivedTime;
if (!packet->wrapper.ParseFromArray(buf, size)) {
fprintf(stderr,
"NewRefereeModule: got bad packet of %d bytes from %s:%d\n",
(int)size, (const char*)host.toString().toLatin1(), port);
fprintf(stderr, "Packet: %s\n", buf);
fprintf(stderr, "Address: %s\n", RefereeAddress);
continue;
}
_mutex.lock();
_packets.push_back(packet);
stage = (Stage)packet->wrapper.stage();
command = (Command)packet->wrapper.command();
sent_time = packet->wrapper.packet_timestamp();
stage_time_left = packet->wrapper.stage_time_left();
command_counter = packet->wrapper.command_counter();
command_timestamp = packet->wrapper.command_timestamp();
yellow_info.ParseRefboxPacket(packet->wrapper.yellow());
blue_info.ParseRefboxPacket(packet->wrapper.blue());
ballPlacementx = packet->wrapper.designated_position().x();
ballPlacementy = packet->wrapper.designated_position().y();
_mutex.unlock();
}
}
示例10: stateChangedSpy
void tst_QUdpSocket::unconnectedServerAndClientTest()
{
QUdpSocket serverSocket;
qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
QSignalSpy stateChangedSpy(&serverSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
QVERIFY2(serverSocket.bind(), serverSocket.errorString().toLatin1().constData());
QCOMPARE(stateChangedSpy.count(), 1);
const char *message[] = {"Yo mista", "Yo", "Wassap"};
QHostAddress serverAddress = QHostAddress::LocalHost;
if (!(serverSocket.localAddress() == QHostAddress::Any))
serverAddress = serverSocket.localAddress();
for (int i = 0; i < 3; ++i) {
QUdpSocket clientSocket;
QCOMPARE(int(clientSocket.writeDatagram(message[i], strlen(message[i]),
serverAddress, serverSocket.localPort())),
int(strlen(message[i])));
char buf[1024];
QHostAddress host;
quint16 port;
QVERIFY(serverSocket.waitForReadyRead(5000));
QCOMPARE(int(serverSocket.readDatagram(buf, sizeof(buf), &host, &port)),
int(strlen(message[i])));
buf[strlen(message[i])] = '\0';
QCOMPARE(QByteArray(buf), QByteArray(message[i]));
}
}
示例11: on_m_pbSend_clicked
void SocketTestWindow::on_m_pbSend_clicked()
{
QString data = ui->m_teSendData->toPlainText();
if(data.length() == 0)
{
return ;
}
QByteArray array;
array.append(data);
if(m_isServer)
{
m_socketBase->sendData(array);
}
else
{
if(m_tcpEnable)
{
if(m_socketClient)
m_socketClient->write(array);
}
else
{
QUdpSocket* udpSocket = dynamic_cast<QUdpSocket*>(m_socketClient);
if(udpSocket)
udpSocket->write(array);
}
}
}
示例12: QTcpServer
void ArduinoThread::run() {
serv = new QTcpServer(this);
connect(serv, SIGNAL(newConnection()), this, SLOT(NewConnection()));
serv->listen(QHostAddress::Any, 34543);
QProcess proc;
proc.start("/sbin/ifconfig");
proc.waitForFinished();
QString ifconfigOutput = proc.readAllStandardOutput();
QString strAddress;
QRegExp rx("addr:([^ ]+)");
int offset = 0;
while(-1 != (rx.indexIn(ifconfigOutput, offset))) {
offset += rx.matchedLength();
strAddress = "[" + rx.cap(1) + "]";
if(strAddress == "[127.0.0.1]")
continue;
if(!strAddress.contains(QRegExp("\\[\\d+\\.\\d+\\.\\d+\\.\\d+\\]")))
continue;
break;
}
QUdpSocket *udpSocket = new QUdpSocket(this);
udpSocket->writeDatagram(strAddress.toAscii(), QHostAddress::Broadcast, 12345);
exec();
}
示例13: sendMessage
bool RemoteInterfaceSender::sendMessage(RemoteInterfaceMessage* message) {
// Do we have a valid destination?
if(message && message->destinationIp != "" && message->destinationPort != 0) {
// Init socket
QUdpSocket socket;
if(!socket.bind(QHostAddress(server->ip), server->port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
// Show error
Debug::error("[RemoteInterfaceSender] could not bind");
return false;
} else {
// Add port and ip keys
if(socket.localAddress().toString() != server->ip) message->properties->insert("reply-ip",socket.localAddress().toString());
if(socket.localPort() != server->port) message->properties->insert("reply-port",QString("%1").arg(socket.localPort()));
// Write to socket
socket.writeDatagram(message->toString().toAscii(), QHostAddress(message->destinationIp), message->destinationPort);
// Add to sent list
server->addMessageToSent(message);
// Show what happened
Debug::print("[RemoteInterfaceSender] sent %1 message to %2:%3", message->type, message->destinationIp, message->destinationPort);
return true;
}
} else {
// Show error
Debug::warning("[RemoteInterfaceSender] message destination must be specified!");
return false;
}
}
示例14: QObject
OceanSocket::OceanSocket(QObject *parent) :
QObject(parent)
{
// setup the heartbeat timer
heartbeat = new QTimer(this);
connect(heartbeat, SIGNAL(timeout()), this, SLOT(heartbeatTimer()));
// setup our ocean sockets
groupAddress = QHostAddress(MULTICAST_ADDRESS);
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
for (int i = 0; i < ifaces.count(); i++) {
QNetworkInterface iface = ifaces.at(i);
if (iface.flags().testFlag(QNetworkInterface::IsUp) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack) && iface.flags().testFlag(QNetworkInterface::CanMulticast)) {
for (int j = 0; j < iface.addressEntries().count(); j++) {
if (iface.addressEntries().at(j).ip().protocol() != QAbstractSocket::IPv4Protocol) continue;
qDebug() << "Ocean bind to iface: " << iface.name() << endl << "IP: " << iface.addressEntries().at(j).ip().toString() << endl;
QUdpSocket* socket = new QUdpSocket(this);
socket->bind(QHostAddress::AnyIPv4, 8047, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
socket->joinMulticastGroup(groupAddress, iface);
connect(socket, SIGNAL(readyRead()), this, SLOT(processIncomingWaves()));
boundAddresses.append(iface.addressEntries().at(j).ip());
multicastSockets.append(socket);
}
}
}
sendSocket = new QUdpSocket(this);
sendSocket->bind();
}
示例15: readPendingAudioRcvrData
void AudioReceiver::readPendingAudioRcvrData() {
QUdpSocket *socket = qobject_cast<QUdpSocket *>(sender());
while (socket->hasPendingDatagrams()) {
m_datagram.resize(socket->pendingDatagramSize());
if (socket->readDatagram(m_datagram.data(), m_datagram.size()) < 0) {
AUDIO_RECEIVER << "read client" << m_client << "socket failed.";
if (io->rcveIQ_toggle) { // toggles the rcveIQ signal
emit rcveIQEvent(this, 2);
io->rcveIQ_toggle = false;
}
}
else {
io->au_queue.enqueue(m_datagram);
if (!io->rcveIQ_toggle) { // toggles the rcveIQ signal
emit rcveIQEvent(this, 1);
io->rcveIQ_toggle = true;
}
}
}
}