예제 #1
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTcpServer server;
    if (!server.listen(QHostAddress::LocalHost, 49199)) {
        qDebug("Failed to listen: %s", server.errorString().toLatin1().constData());
        return 1;
    }

#if defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN)
    QFile file(QLatin1String("/test_signal.txt"));
    file.open(QIODevice::WriteOnly);
    file.write("Listening\n");
    file.flush();
    file.close();
#else
    printf("Listening\n");
    fflush(stdout);
#endif

    server.waitForNewConnection(5000);
    qFatal("Crash");
    return 0;
}
예제 #2
0
void QListenerThread::HandleAcceptError( QAbstractSocket::SocketError socketError )
{
    QTcpServer* pServer =( QTcpServer* ) sender( );
    Q_UNUSED( socketError )
    QString strLog = pServer->errorString( );
    SendLog( strLog, true );
}
예제 #3
0
void tst_QTcpServer::proxyFactory()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QFETCH(QList<QNetworkProxy>, proxyList);
    QFETCH(QNetworkProxy, proxyUsed);
    QFETCH(bool, fails);

    MyProxyFactory *factory = new MyProxyFactory;
    factory->toReturn = proxyList;
    QNetworkProxyFactory::setApplicationProxyFactory(factory);

    QTcpServer server;
    bool listenResult = server.listen();

    // Verify that the factory was called properly
    QCOMPARE(factory->callCount, 1);
    QCOMPARE(factory->lastQuery, QNetworkProxyQuery(0, QString(), QNetworkProxyQuery::TcpServer));

    QCOMPARE(listenResult, !fails);
    QCOMPARE(server.errorString().isEmpty(), !fails);

    // note: the following test is not a hard failure.
    // Sometimes, error codes change for the better
    QTEST(int(server.serverError()), "expectedError");
}
예제 #4
0
bool DesignerExternalEditor::startEditor(const QString &fileName, QString *errorMessage)
{
    EditorLaunchData data;
    // Find the editor binary
    if (!getEditorLaunchData(fileName, &QtSupport::BaseQtVersion::designerCommand,
                            QLatin1String(designerBinaryC),
                            QStringList(), false, &data, errorMessage)) {
        return false;
    }
    // Known one?
    const ProcessCache::iterator it = m_processCache.find(data.binary);
    if (it != m_processCache.end()) {
        // Process is known, write to its socket to cause it to open the file
        if (debug)
           qDebug() << Q_FUNC_INFO << "\nWriting to socket:" << data.binary << fileName;
        QTcpSocket *socket = it.value();
        if (!socket->write(fileName.toUtf8() + '\n')) {
            *errorMessage = tr("Qt Designer is not responding (%1).").arg(socket->errorString());
            return false;
        }
        return true;
    }
    // No process yet. Create socket & launch the process
    QTcpServer server;
    if (!server.listen(QHostAddress::LocalHost)) {
        *errorMessage = tr("Unable to create server socket: %1").arg(server.errorString());
        return false;
    }
    const quint16 port = server.serverPort();
    if (debug)
        qDebug() << Q_FUNC_INFO << "\nLaunching server:" << port << data.binary << fileName;
    // Start first one with file and socket as '-client port file'
    // Wait for the socket listening
    data.arguments.push_front(QString::number(port));
    data.arguments.push_front(QLatin1String("-client"));

    if (!startEditorProcess(data, errorMessage))
        return false;
    // Set up signal mapper to track process termination via socket
    if (!m_terminationMapper) {
        m_terminationMapper = new QSignalMapper(this);
        connect(m_terminationMapper, SIGNAL(mapped(QString)), this, SLOT(processTerminated(QString)));
    }
    // Insert into cache if socket is created, else try again next time
    if (server.waitForNewConnection(3000)) {
        QTcpSocket *socket = server.nextPendingConnection();
        socket->setParent(this);
        m_processCache.insert(data.binary, socket);
        m_terminationMapper->setMapping(socket, data.binary);
        connect(socket, SIGNAL(disconnected()), m_terminationMapper, SLOT(map()));
        connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), m_terminationMapper, SLOT(map()));
    }
    return true;
}
예제 #5
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::listenError()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy) {
        QFETCH_GLOBAL(int, proxyType);
        if (proxyType == QNetworkProxy::Socks5Proxy) {
            QSKIP("With socks5 we can not make hard requirements on the address or port", SkipAll);
        }
    }
    QTcpServer server;
    QVERIFY(!server.listen(QHostAddress("1.2.3.4"), 0));
    QCOMPARE(server.serverError(), QAbstractSocket::SocketAddressNotAvailableError);
    QCOMPARE(server.errorString().toLatin1().constData(), "The address is not available");
}
예제 #6
0
void tst_QTcpServer::invalidProxy()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QFETCH(int, type);
    QFETCH(QString, host);
    QFETCH(int, port);
    QNetworkProxy::ProxyType proxyType = QNetworkProxy::ProxyType(type);
    QNetworkProxy proxy(proxyType, host, port);

    QTcpServer server;
    server.setProxy(proxy);
    bool listenResult = server.listen();

    QVERIFY(!listenResult);
    QVERIFY(!server.errorString().isEmpty());

    // note: the following test is not a hard failure.
    // Sometimes, error codes change for the better
    QTEST(int(server.serverError()), "expectedError");
}
예제 #7
0
//*******************************************************************************
// Now that the first handshake is with TCP server, if the addreess/peer port of
// the client is already on the thread pool, it means that a new connection is
// requested (the old was desconnected). So we have to remove that thread from
// the pool and then connect again.
void UdpMasterListener::run()
{
  mStopped = false;

  QHostAddress PeerAddress; // Object to store peer address
  int peer_udp_port; // Peer listening port
  int server_udp_port; // Server assigned udp port

  // Create and bind the TCP server
  // ------------------------------
  QTcpServer TcpServer;
  if ( !TcpServer.listen(QHostAddress::Any, mServerPort) ) {
    std::cerr << "TCP Socket Server ERROR: " << TcpServer.errorString().toStdString() <<  endl;
    std::exit(1);
  }

  const int tcpTimeout = 5*1000;


  cout << "JackTrip MULTI-THREADED SERVER: TCP Server Listening in Port = " << TcpServer.serverPort() << endl;
  while ( !mStopped )
  {
    cout << "JackTrip MULTI-THREADED SERVER: Waiting for client connections..." << endl;
    cout << "=======================================================" << endl;
    while ( !TcpServer.waitForNewConnection(1000) )
    { if (mStopped) { return; } } // block until a new connection is received
    cout << "JackTrip MULTI-THREADED SERVER: Client Connection Received!" << endl;

    // Control loop to be able to exit if UDPs or TCPs error ocurr
    for (int dum = 0; dum<1; dum++) {
      QTcpSocket *clientConnection = TcpServer.nextPendingConnection();
      if ( !clientConnection->waitForConnected(tcpTimeout) ) {
        std::cerr << clientConnection->errorString().toStdString() << endl;
        break;
      }
      PeerAddress = clientConnection->peerAddress();
      cout << "JackTrip MULTI-THREADED SERVER: Client Connect Received from Address : "
          << PeerAddress.toString().toStdString() << endl;

      // Get UDP port from client
      // ------------------------
      peer_udp_port = readClientUdpPort(clientConnection);
      if ( peer_udp_port == 0 ) { break; }
      cout << "JackTrip MULTI-THREADED SERVER: Client UDP Port is = " << peer_udp_port << endl;

      // Check is client is new or not
      // -----------------------------
      // Check if Address is not already in the thread pool
      // check by comparing 32-bit addresses
      int id = isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port);
      // If the address is not new, we need to remove the client from the pool
      // before re-starting the connection
      if (id == -1) {
        int id_remove;
        id_remove = getPoolID(PeerAddress.toIPv4Address(), peer_udp_port);
        // stop the thread
        mJTWorkers->at(id_remove)->stopThread();
        // block until the thread has been removed from the pool
        while ( isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port) == -1 ) {
          cout << "JackTrip MULTI-THREADED SERVER: Removing JackTripWorker from pool..." << endl;
          QThread::msleep(10);
        }
        // Get a new ID for this client
        //id = isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port);
        id = getPoolID(PeerAddress.toIPv4Address(), peer_udp_port);
      }
      // Assign server port and send it to Client
      server_udp_port = mBasePort+id;
      if ( sendUdpPort(clientConnection, server_udp_port) == 0 ) {
        clientConnection->close();
        delete clientConnection;
        releaseThread(id);
        break;
      }

      // Close and Delete the socket
      // ---------------------------
      clientConnection->close();
      delete clientConnection;
      cout << "JackTrip MULTI-THREADED SERVER: Client TCP Socket Closed!" << endl;

      // Spawn Thread to Pool
      // --------------------
      // Register JackTripWorker with the master listener
      delete mJTWorkers->at(id); // just in case the Worker was previously created
      mJTWorkers->replace(id, new JackTripWorker(this));
      // redirect port and spawn listener
      cout << "---> JackTrip MULTI-THREADED SERVER: Spawning Listener..." << endl;
      {
        QMutexLocker lock(&mMutex);
        mJTWorkers->at(id)->setJackTrip(id, mActiveAddress[id][0],
                                        server_udp_port, mActiveAddress[id][1],
                                        1); /// \todo temp default to 1 channel
      }
      //send one thread to the pool
      cout << "---> JackTrip MULTI-THREADED SERVER: Starting Thread..." << endl;
      mThreadPool.start(mJTWorkers->at(id), QThread::TimeCriticalPriority);
      // wait until one is complete before another spawns
      while (mJTWorkers->at(id)->isSpawning()) { QThread::msleep(10); }
      //mTotalRunningThreads++;
      cout << "JackTrip MULTI-THREADED SERVER: Total Running Threads:  " << mTotalRunningThreads << endl;
      cout << "===============================================================" << endl;
      QThread::msleep(100);
    }
  }

  /*
  // Create objects on the stack
  QUdpSocket MasterUdpSocket;
  QHostAddress PeerAddress;
  uint16_t peer_port; // Ougoing Peer port, in case they're not using the default

  // Bind the socket to the well known port
  bindUdpSocket(MasterUdpSocket, mServerPort);

  char buf[1];
  cout << "Server Listening in UDP Port: " << mServerPort << endl;
  cout << "Waiting for client..." << endl;
  cout << "=======================================================" << endl;
  while ( !mStopped )
  {
    //cout << "WAITING........................." << endl;
    while ( MasterUdpSocket.hasPendingDatagrams() )
    {
      cout << "Received request from Client!" << endl;
      // Get Client IP Address and outgoing port from packet
      int rv = MasterUdpSocket.readDatagram(buf, 1, &PeerAddress, &peer_port);
      cout << "Peer Port in Server ==== " << peer_port << endl;
      if (rv < 0) { std::cerr << "ERROR: Bad UDP packet read..." << endl; }

      /// \todo Get number of channels in the client from header

      // check by comparing 32-bit addresses
      /// \todo Add the port number in the comparison
      cout << "peer_portpeer_portpeer_port === " << peer_port << endl;
      int id = isNewAddress(PeerAddress.toIPv4Address(), peer_port);

      //cout << "IDIDIDIDIDDID === " << id << endl;

      // If the address is new, create a new thread in the pool
      if (id >= 0) // old address is -1
      {
        // redirect port and spawn listener
        sendToPoolPrototype(id);
        // wait until one is complete before another spawns
        while (mJTWorker->isSpawning()) { QThread::msleep(10); }
        mTotalRunningThreads++;
        cout << "Total Running Threads:  " << mTotalRunningThreads << endl;
        cout << "=======================================================" << endl;
      }
      //cout << "ENDDDDDDDDDDDDDDDDDd === " << id << endl;
    }
    QThread::msleep(100);
  }
  */
}