本文整理汇总了C++中QUdpSocket::writeDatagram方法的典型用法代码示例。如果您正苦于以下问题:C++ QUdpSocket::writeDatagram方法的具体用法?C++ QUdpSocket::writeDatagram怎么用?C++ QUdpSocket::writeDatagram使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QUdpSocket
的用法示例。
在下文中一共展示了QUdpSocket::writeDatagram方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: 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;
}
}
示例2:
/*
* 析构时发送"我离开了"的消息
* 因为进行到窗口的析构函数时,子对象都已经被删除,故而不能使用_sender成员进行发送
*/
ChatWindow::~ChatWindow()
{
QUdpSocket tmpSocket;
QByteArray bytes=pack_Leave(_username,getIPv4());
tmpSocket.writeDatagram(bytes,bytes.length(),QHostAddress::Broadcast,_port);
delete ui;
}
示例3: send
void LinkQuality::send()
{
cout<<"send"<<endl;
int size = packetLengthEdit->text().toInt();
int count = countEdit->text().toInt();
//write message to log file
gpsLock.lockForRead();
fileLock.lockForWrite();
*logFile<<"*********************************************"<<endl;
*logFile<<"local:"<<endl<<" "<<this->time.toAscii()<<" "<<this->longitude.toAscii()<<" "<<latitude.toAscii()
<<" "<<count<<" "<<size<<endl;
fileLock.unlock();
gpsLock.unlock();
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out<<qint16(1);
datagram.resize(size);
cout<<datagram.size()<<endl;
QUdpSocket sendSocket;
for(int i = 0; i < count; i++)
{
sendSocket.writeDatagram(datagram, datagram.size(), QHostAddress(remoteAddr), CMD_PORT);
//sleep(1);
}
}
示例4: run
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();
}
示例5: process
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();
}
}
示例6: unconnectedServerAndClientTest
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]));
}
}
示例7: Broadcast
QString connection::Broadcast() {
// Om ip adressen te ontdekken
QNetworkAddressEntry inter;
// sockets aanmaken en verbinden met enerzijds broadcast en anderzijds een luister poort
QUdpSocket udpSocketSend;
QUdpSocket udpSocketGet;
udpSocketSend.connectToHost(inter.broadcast(), 40000);
// udpSocketGet->bind(inter->ip(),667);
// udpSocketGet->bind(QHostAddress::Any,667)
if(udpSocketGet.bind(udpgetport,QUdpSocket::ShareAddress))
Label->setText(Label->text() + "[INFO] Could properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
else Label->setText(Label->text() + "[INFO] Couldn't properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
// Pakket verzenden
QByteArray send_datagram = "DISCOVER-STRATEGO-SERVER";
// Optimalisatie voor in de loop
QByteArray receive_datagram;
quint16 serverPort;
forever{
udpSocketSend.writeDatagram(send_datagram, QHostAddress::Broadcast, 40000);
if(udpSocketGet.waitForReadyRead(3000)){
receive_datagram.resize(udpSocketGet.pendingDatagramSize());
udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
if(QString::fromUtf8(receive_datagram.data()) == "DISCOVERED-STRATEGO-SERVER")
{
receive_datagram.resize(udpSocketGet.pendingDatagramSize());
udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
Label->setText(Label->text() +"[INFO] PLAYER DATA: "+ receive_datagram.data() +"\n");
speler = receive_datagram.toInt();
if(speler==1)
{
attacker=true;
}
else
{
attacker=false;
}
receive_datagram.resize(udpSocketGet.pendingDatagramSize());
udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
Label->setText(Label->text() + "[INFO] GAME DATA: "+receive_datagram.data()+"\n");
spel = receive_datagram.toInt();
Label->setText(Label->text() + " SPEL:" + QString::number(spel) + "\n");
Label->setText(Label->text() + "[INFO] Found STRATEGO-SERVER on " + server.toString().toUtf8().constData() + "\n");
return server.toString();
}
}
else
{
Label->setText(Label->text() + "[INFO] UDP Discover TimeOut!\n");
static int timeout=0;
timeout++;
if(timeout==5)
{
Label->setText(Label->text() + "[ERROR] Server is not online. Please try again later!");
return "";
}
}
}
return "";
}
示例8: 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
}
示例9: pendingDatagramSize
void tst_QUdpSocket::pendingDatagramSize()
{
QUdpSocket server;
QVERIFY2(server.bind(), server.errorString().toLatin1().constData());
QHostAddress serverAddress = QHostAddress::LocalHost;
if (!(server.localAddress() == QHostAddress::Any))
serverAddress = server.localAddress();
QUdpSocket client;
QVERIFY(client.writeDatagram("this is", 7, serverAddress, server.localPort()) == 7);
QVERIFY(client.writeDatagram(0, 0, serverAddress, server.localPort()) == 0);
QVERIFY(client.writeDatagram("3 messages", 10, serverAddress, server.localPort()) == 10);
char c = 0;
QVERIFY(server.waitForReadyRead());
if (server.hasPendingDatagrams()) {
#if defined Q_OS_HPUX && defined __ia64
QEXPECT_FAIL("", "HP-UX 11i v2 can't determine the datagram size correctly.", Abort);
#endif
QCOMPARE(server.pendingDatagramSize(), qint64(7));
c = '\0';
QCOMPARE(server.readDatagram(&c, 1), qint64(1));
QCOMPARE(c, 't');
c = '\0';
} else {
QSKIP("does not have the 1st datagram", SkipSingle);
}
if (server.hasPendingDatagrams()) {
QCOMPARE(server.pendingDatagramSize(), qint64(0));
QCOMPARE(server.readDatagram(&c, 1), qint64(0));
QCOMPARE(c, '\0'); // untouched
c = '\0';
} else {
QSKIP("does not have the 2nd datagram", SkipSingle);
}
if (server.hasPendingDatagrams()) {
QCOMPARE(server.pendingDatagramSize(), qint64(10));
QCOMPARE(server.readDatagram(&c, 1), qint64(1));
QCOMPARE(c, '3');
} else {
QSKIP("does not have the 3rd datagram", SkipSingle);
}
}
示例10: run
/**
* @brief TransmitterTask::run
*/
void TransmitterTask::run()
{
QUdpSocket socket;
socket.bind(port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
socket.writeDatagram(data, address, port);
socket.waitForBytesWritten();
socket.close();
qDebug() << "Task:" << address << ':' << port << "<-" << data;
}
示例11: QFETCH
void tst_QUdpSocket::ipv6Loop()
{
QFETCH(QByteArray, peterMessage);
QFETCH(QByteArray, paulMessage);
QFETCH(bool, success);
QUdpSocket peter;
QUdpSocket paul;
quint16 peterPort = 28124;
quint16 paulPort = 28123;
if (!peter.bind(QHostAddress::LocalHostIPv6, peterPort)) {
QCOMPARE(peter.error(), QUdpSocket::UnsupportedSocketOperationError);
} else {
QVERIFY(paul.bind(QHostAddress::LocalHostIPv6, paulPort));
QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(), QHostAddress("::1"),
paulPort), qint64(peterMessage.length()));
QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
QHostAddress("::1"), peterPort), qint64(paulMessage.length()));
char peterBuffer[16*1024];
char paulBuffer[16*1024];
#if !defined(Q_OS_WINCE)
QVERIFY(peter.waitForReadyRead(5000));
QVERIFY(paul.waitForReadyRead(5000));
#else
QVERIFY(peter.waitForReadyRead(15000));
QVERIFY(paul.waitForReadyRead(15000));
#endif
if (success) {
QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
} else {
QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
}
QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
}
}
示例12: broadcasting
void tst_QUdpSocket::broadcasting()
{
QFETCH_GLOBAL(bool, setProxy);
if (setProxy) {
#ifdef TEST_QNETWORK_PROXY
QFETCH_GLOBAL(int, proxyType);
if (proxyType == QNetworkProxy::Socks5Proxy) {
QSKIP("With socks5 Broadcast is not supported.", SkipAll);
}
#endif
}
#ifdef Q_OS_AIX
QSKIP("Broadcast does not work on darko", SkipAll);
#endif
const char *message[] = {"Yo mista", "", "Yo", "Wassap"};
for (int i = 0; i < 4; ++i) {
QUdpSocket serverSocket;
QVERIFY2(serverSocket.bind(QHostAddress::Any, 5000), serverSocket.errorString().toLatin1().constData());
QCOMPARE(serverSocket.state(), QUdpSocket::BoundState);
connect(&serverSocket, SIGNAL(readyRead()), SLOT(empty_readyReadSlot()));
QUdpSocket broadcastSocket;
for (int j = 0; j < 100; ++j) {
broadcastSocket.writeDatagram(message[i], strlen(message[i]),
QHostAddress::Broadcast, 5000);
QTestEventLoop::instance().enterLoop(15);
if (QTestEventLoop::instance().timeout()) {
#if defined(Q_OS_FREEBSD)
QEXPECT_FAIL("",
"Broadcasting to 255.255.255.255 does not work on FreeBSD",
Abort);
QVERIFY(false); // seems that QFAIL() doesn't respect the QEXPECT_FAIL() :/
#endif
QFAIL("Network operation timed out");
}
QVERIFY(serverSocket.hasPendingDatagrams());
do {
QByteArray arr;
arr.resize(serverSocket.pendingDatagramSize() + 1);
QHostAddress host;
quint16 port;
QCOMPARE((int) serverSocket.readDatagram(arr.data(), arr.size() - 1, &host, &port),
(int) strlen(message[i]));
arr.resize(strlen(message[i]));
QCOMPARE(arr, QByteArray(message[i]));
} while (serverSocket.hasPendingDatagrams());
}
}
}
示例13: wakeup
void DevicePluginWakeOnLan::wakeup(QString mac)
{
const char header[] = {char(0xff), char(0xff), char(0xff), char(0xff), char(0xff), char(0xff)};
QByteArray packet = QByteArray::fromRawData(header, sizeof(header));
for(int i = 0; i < 16; ++i) {
packet.append(QByteArray::fromHex(mac.remove(':').toLocal8Bit()));
}
qCDebug(dcWakeOnLan) << "Created magic packet:" << packet.toHex();
QUdpSocket udpSocket;
udpSocket.writeDatagram(packet.data(), packet.size(), QHostAddress::Broadcast, 9);
}
示例14: SendMessage
bool Myth::SendMessage( const QString &sMessage,
const QString &sAddress,
int udpPort,
int Timeout)
{
bool bResult = false;
if (sMessage.isEmpty())
return bResult;
if (Timeout < 0 || Timeout > 999)
Timeout = 0;
QString xmlMessage =
"<mythmessage version=\"1\">\n"
" <text>" + sMessage + "</text>\n"
" <timeout>" + QString::number(Timeout) + "</timeout>\n"
"</mythmessage>";
QHostAddress address = QHostAddress::Broadcast;
unsigned short port = 6948;
if (!sAddress.isEmpty())
address.setAddress(sAddress);
if (udpPort != 0)
port = udpPort;
QUdpSocket *sock = new QUdpSocket();
QByteArray utf8 = xmlMessage.toUtf8();
int size = utf8.length();
if (sock->writeDatagram(utf8.constData(), size, address, port) < 0)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Failed to send UDP/XML packet (Message: %1 "
"Address: %2 Port: %3")
.arg(sMessage).arg(sAddress).arg(port));
}
else
{
LOG(VB_GENERAL, LOG_DEBUG,
QString("UDP/XML packet sent! (Message: %1 Address: %2 Port: %3")
.arg(sMessage)
.arg(address.toString().toLocal8Bit().constData()).arg(port));
bResult = true;
}
sock->deleteLater();
return bResult;
}
示例15: loop
void tst_QUdpSocket::loop()
{
QFETCH(QByteArray, peterMessage);
QFETCH(QByteArray, paulMessage);
QFETCH(bool, success);
QUdpSocket peter;
QUdpSocket paul;
QVERIFY2(peter.bind(), peter.errorString().toLatin1().constData());
QVERIFY2(paul.bind(), paul.errorString().toLatin1().constData());
QHostAddress peterAddress = QHostAddress::LocalHost;
if (!(peter.localAddress() == QHostAddress::Any))
peterAddress = peter.localAddress();
QHostAddress pualAddress = QHostAddress::LocalHost;
if (!(paul.localAddress() == QHostAddress::Any))
pualAddress = paul.localAddress();
QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(),
pualAddress, paul.localPort()), qint64(peterMessage.length()));
QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
peterAddress, peter.localPort()), qint64(paulMessage.length()));
QVERIFY(peter.waitForReadyRead(5000));
QVERIFY(paul.waitForReadyRead(5000));
char peterBuffer[16*1024];
char paulBuffer[16*1024];
if (success) {
QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
} else {
QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
}
QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
}