本文整理汇总了C++中QUdpSocket::connectToHost方法的典型用法代码示例。如果您正苦于以下问题:C++ QUdpSocket::connectToHost方法的具体用法?C++ QUdpSocket::connectToHost怎么用?C++ QUdpSocket::connectToHost使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QUdpSocket
的用法示例。
在下文中一共展示了QUdpSocket::connectToHost方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: 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 "";
}
示例2: getNTPTime
void TimeSync::getNTPTime()
{
QUdpSocket sock;
sock.connectToHost("0.pool.ntp.org",123);
if(!sock.waitForConnected(1000))return;
QByteArray data(48,char(0)); *(reinterpret_cast<qint32 *>(&data.data()[0]))=4194959577;
if(sock.write(data)<0||!sock.waitForReadyRead(3000)||sock.bytesAvailable()!=48)return;
data=sock.readAll();
quint32 seconds=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[40])));
quint32 fraction=qToBigEndian(*(reinterpret_cast<quint32 *>(&data.data()[44])));
quint32 newTime=QDateTime::fromMSecsSinceEpoch(seconds*1000ll+fraction*1000ll/0x100000000ll-2208988800000ll).toTime_t();
if(newTime<1451606400 || newTime>4000000000){
QThread::msleep(500);
emit startSync();
return;
}
qint32 tempTimeShift=qint64(newTime)-qint64(QDateTime::currentDateTime().toTime_t());
if(timeShift!=0)tempTimeShift=qint32((qint64(timeShift)+qint64(tempTimeShift))/2);
if(tempTimeShift>3600 || tempTimeShift<-3600){
static bool showMessage=true;
if(showMessage)emit warningMessage(julyTr("TIME_SYNC_ERROR","Your clock is not set. Please close the Qt Bitcoin Trader and set the clock. Changing time at Qt Bitcoin Trader enabled can cause errors and damage the keys."));
showMessage=false;
}
else
timeShift.fetchAndStoreOrdered(tempTimeShift);
getNTPTimeRetryCount++;
if(getNTPTimeRetryCount<3)emit startSync();
}
示例3: sendToEditor
bool EditorPipe::sendToEditor(QString command)
{
QUdpSocket socket;
// Attempt to connect to the LocalServer
socket.connectToHost(QHostAddress::LocalHost, 58487);
if(socket.waitForConnected(100))
{
qDebug() << "Connected";
QString str = QString(command);
QByteArray bytes;
bytes = str.toUtf8();
socket.write(bytes);
socket.waitForBytesWritten(10000);
socket.flush();
socket.disconnectFromHost();
qDebug() << "Bytes sent: " <<command;
return true;
}
else
{
qDebug() << "sendToEditor(QString command) fail to connect: " << socket.errorString();
return false;
}
}
示例4: performance
void tst_QUdpSocket::performance()
{
QUdpSocket server;
QVERIFY2(server.bind(), server.errorString().toLatin1().constData());
QHostAddress serverAddress = QHostAddress::LocalHost;
if (!(server.localAddress() == QHostAddress::Any))
serverAddress = server.localAddress();
QUdpSocket client;
client.connectToHost(serverAddress, server.localPort());
QByteArray arr(8192, '@');
QTime stopWatch;
stopWatch.start();
qint64 nbytes = 0;
while (stopWatch.elapsed() < 5000) {
for (int i = 0; i < 100; ++i) {
if (client.write(arr.data(), arr.size()) > 0) {
do {
nbytes += server.readDatagram(arr.data(), arr.size());
} while (server.hasPendingDatagrams());
}
}
}
float secs = stopWatch.elapsed() / 1000.0;
qDebug("\t%.2fMB/%.2fs: %.2fMB/s", float(nbytes / (1024.0*1024.0)),
secs, float(nbytes / (1024.0*1024.0)) / secs);
}
示例5: writeToNonExistingPeer
void tst_QUdpSocket::writeToNonExistingPeer()
{
QSKIP("Connected-mode UDP sockets and their behaviour are erratic", SkipAll);
QFETCH(QHostAddress, peerAddress);
quint16 peerPort = 34534;
qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
QUdpSocket sConnected;
QSignalSpy sConnectedReadyReadSpy(&sConnected, SIGNAL(readyRead()));
QSignalSpy sConnectedErrorSpy(&sConnected, SIGNAL(error(QAbstractSocket::SocketError)));
sConnected.connectToHost(peerAddress, peerPort, QIODevice::ReadWrite);
// the first write succeeds...
QCOMPARE(sConnected.write("", 1), qint64(1));
// the second one should fail!
QTest::qSleep(1000); // do not process events
QCOMPARE(sConnected.write("", 1), qint64(-1));
QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
// the third one will succeed...
QCOMPARE(sConnected.write("", 1), qint64(1));
QTestEventLoop::instance().enterLoop(1);
QCOMPARE(sConnectedReadyReadSpy.count(), 0);
QCOMPARE(sConnectedErrorSpy.count(), 1);
QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
// we should now get a read error
QCOMPARE(sConnected.write("", 1), qint64(1));
QTest::qSleep(1000); // do not process events
char buf[2];
QVERIFY(!sConnected.hasPendingDatagrams());
QCOMPARE(sConnected.bytesAvailable(), Q_INT64_C(0));
QCOMPARE(sConnected.pendingDatagramSize(), Q_INT64_C(-1));
QCOMPARE(sConnected.readDatagram(buf, 2), Q_INT64_C(-1));
QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
QCOMPARE(sConnected.write("", 1), qint64(1));
QTest::qSleep(1000); // do not process events
QCOMPARE(sConnected.read(buf, 2), Q_INT64_C(0));
QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
// we should still be connected
QCOMPARE(int(sConnected.state()), int(QUdpSocket::ConnectedState));
}
示例6: connect
inline static void connect()
{
socket_.connectToHost(QHostAddress(QHostAddress::LocalHost), PORT);
}
示例7: createDevice
/**
* @details
* Creates an open UDP socket. The socket will be deleted by the base class.
*/
QIODevice* AbstractUdpEmulator::createDevice()
{
QUdpSocket* socket = new QUdpSocket;
socket->connectToHost(_host, _port);
return socket;
}
示例8: udp_ping
int udp_ping(QStringList command) {
qDebug() << "udp_ping(" << command.join(" ") << ")" << endl;
qDebug() << "udp_ping(" << command.join(" ") << ")" << endl;
/**
* Check input
*/
QTextStream errorStream(stderr);
if(command.size() != 3 || command.at(0)!="ping" || command.at(1)!="udp" ) {
errorStream << "Error: udp_ping(" << command.join(" ") << ") is no valid call (ping udp <ip_address> <port> rzv|max|random|default)" << endl;
return 1;
}
/**
* <functionality>
*/
QByteArray byteArray;
/**
* CIP for "rzv"
*/
if(command.at(2)=="rzv") {
qDebug() << "rzv" << endl;
byteArray.append(QByteArray(42, '\0'));
}
/**
* Sent via TCP
*/
QUdpSocket *udpSocket;
udpSocket = new QUdpSocket();
QTextStream outStream(stdout);
QString out;
udpSocket->abort();
udpSocket->connectToHost("127.0.0.1", 22366);
qDebug() << "waitForConnected!";
if (udpSocket->waitForConnected(5000)) {
qDebug() << "Connected!";
}
else {
errorStream << "Error: udp_ping(" << command.join(" ") << "): No connection available!" << endl;
return 1;
}
qDebug() << QString("BytesWritten: %1").arg(udpSocket->write(byteArray, byteArray.length()));
udpSocket->flush();
int numRead = 0, numReadTotal = 0;
char buffer[MAXMSG];
forever {
numRead = udpSocket->read(buffer, MAXMSG);
qDebug() << "read buffer: " << numRead;
numReadTotal += numRead;
if (numRead <= 0 && !udpSocket->waitForReadyRead(30))
break;
}
qDebug() << numReadTotal << " bytes red";
if(numReadTotal==-1) {
errorStream << "Error: udp_ping(" << command.join(" ") << "): " << udpSocket->errorString() << endl;
return 1;
}
else {
for(int i=0; i < numReadTotal; i++) {
qDebug() << QString("receipt[%1]: %2\n").arg(i).arg(buffer[i], 8, 2, QLatin1Char('0')) << endl;;
}
QByteArray receipt(buffer);
qDebug() << "receipt.size(): " << receipt.size();
for(int i = 0; i < receipt.size();++i) {
qDebug() << QString("receipt[%1]: %2\n").arg(i).arg(receipt.at(i), 8, 2, QLatin1Char('0')) << endl;;
}
qDebug() << "buffer: " << buffer;
}
udpSocket->disconnectFromHost();
udpSocket->close();
outStream << out << endl;
return 0;
}