本文整理汇总了C++中QUdpSocket::bind方法的典型用法代码示例。如果您正苦于以下问题:C++ QUdpSocket::bind方法的具体用法?C++ QUdpSocket::bind怎么用?C++ QUdpSocket::bind使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QUdpSocket
的用法示例。
在下文中一共展示了QUdpSocket::bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: 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();
}
}
示例2: 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]));
}
}
示例3: testSendKeyInputPacket
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;
}
示例4: 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;
}
}
示例5: 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();
}
示例6: 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);
}
示例7: 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();
}
}
示例8: 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 "";
}
示例9: QMainWindow
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
/*connect(&m_tm, SIGNAL(timeout()), this, SLOT(processData()));
m_tm.setInterval(1);
m_tm.start();*/
QTimer *tm = new QTimer(this);
connect(tm, SIGNAL(timeout()), this, SLOT(draw()));
tm->setInterval(1000 / 60);
tm->start();
m_udp.bind(9999);
connect(&m_udp, SIGNAL(readyRead()), this, SLOT(processData()));
ui->visWorld->stat = 0;
ui->visWorld->pdaData = &m_pdaData;
ui->visWorld2->stat = 1;
ui->visWorld2->pdaData = &m_pdaData;
ui->visScreen->pdaData = &m_pdaData;
m_pdaData.sphereEnabled = 0;
ui->widgetSensors->setVisible(true);
ui->widgetSpheres->setVisible(false);
}
示例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: newDevice
// Creates a suitable device ready for reading.
QIODevice* JTestChunker::newDevice()
{
// Return an opened QUdpSocket.
QUdpSocket* socket = new QUdpSocket;
socket->bind(QHostAddress(host()), port());
// Wait for the socket to bind.
while (socket->state() != QUdpSocket::BoundState) {}
return socket;
}
示例13: newDevice
/**
* @details
* Constructs a new QIODevice (in this case a QUdpSocket) and returns it
* after binding the socket to the port specified in the XML node and read by
* the constructor of the abstract chunker.
*/
QIODevice* LofarDataSplittingChunker::newDevice()
{
QUdpSocket* socket = new QUdpSocket;
if (!socket->bind(port(), QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint ))
cerr << "LofarDataSplittingChunker::newDevice(): "
"Unable to bind to UDP port!" <<
socket->errorString().toStdString() << std::endl;
return socket;
}
示例14:
// Constructs a new QIODevice (in this case a QUdpSocket) and returns it
// after binding the socket to the port specified in the XML node and read by
// the constructor of the abstract chunker.
QIODevice* K7Chunker::newDevice()
{
QUdpSocket* udpSocket = new QUdpSocket;
if (!udpSocket->bind(port(), QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint ))
{
std::cerr << "K7Chunker::newDevice(): Unable to bind to UDP port!" << udpSocket->errorString().toStdString() << std::endl;
}
return udpSocket;
}
示例15: 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());
}
}
}