//---------------------------------------------------------------------------------- void tst_QTcpServer::waitForConnectionTest() { QFETCH_GLOBAL(bool, setProxy); if (setProxy) { QFETCH_GLOBAL(int, proxyType); if (proxyType == QNetworkProxy::Socks5Proxy) { QSKIP("Localhost servers don't work well with SOCKS5", SkipAll); } } QTcpSocket findLocalIpSocket; findLocalIpSocket.connectToHost(QtNetworkSettings::serverName(), 143); QVERIFY(findLocalIpSocket.waitForConnected(5000)); QTcpServer server; bool timeout = false; QVERIFY(server.listen(findLocalIpSocket.localAddress())); QVERIFY(!server.waitForNewConnection(1000, &timeout)); QCOMPARE(server.serverError(), QAbstractSocket::SocketTimeoutError); QVERIFY(timeout); ThreadConnector connector(findLocalIpSocket.localAddress(), server.serverPort()); connector.start(); #if defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN) QVERIFY(server.waitForNewConnection(9000, &timeout)); #else QVERIFY(server.waitForNewConnection(3000, &timeout)); #endif QVERIFY(!timeout); }
//---------------------------------------------------------------------------------- void tst_QTcpServer::ipv4PerformanceTest() { QTcpSocket probeSocket; probeSocket.connectToHost(QtNetworkSettings::serverName(), 143); QVERIFY(probeSocket.waitForConnected(5000)); QTcpServer server; QVERIFY(server.listen(probeSocket.localAddress(), 0)); QTcpSocket clientA; clientA.connectToHost(server.serverAddress(), server.serverPort()); QVERIFY(clientA.waitForConnected(5000)); QVERIFY(server.waitForNewConnection(5000)); QTcpSocket *clientB = server.nextPendingConnection(); QVERIFY(clientB); QByteArray buffer(16384, '@'); QTime stopWatch; stopWatch.start(); qlonglong totalWritten = 0; while (stopWatch.elapsed() < 5000) { qlonglong writtenA = clientA.write(buffer.data(), buffer.size()); clientA.flush(); totalWritten += buffer.size(); while (clientB->waitForReadyRead(100)) { if (clientB->bytesAvailable() == writtenA) break; } clientB->read(buffer.data(), buffer.size()); qlonglong writtenB = clientB->write(buffer.data(), buffer.size()); clientB->flush(); totalWritten += buffer.size(); while (clientA.waitForReadyRead(100)) { if (clientA.bytesAvailable() == writtenB) break; } clientA.read(buffer.data(), buffer.size()); } qDebug("\t\t%s: %.1fMB/%.1fs: %.1fMB/s", probeSocket.localAddress().toString().toLatin1().constData(), totalWritten / (1024.0 * 1024.0), stopWatch.elapsed() / 1000.0, (totalWritten / (stopWatch.elapsed() / 1000.0)) / (1024 * 1024)); delete clientB; }
/** *函数介绍:跟踪server端socket状态 *输入参数:服务端socket状态 *返回值:无 */ void TcpServer::getServerSocketState(QAbstractSocket::SocketState socketState) { QTcpSocket *serverSocket = qobject_cast<QTcpSocket *>(sender()); QString clientIp = serverSocket->peerAddress().toString(); int clientPort = serverSocket->peerPort(); QString serverIp = this->serverAddress().toString(); int serverPort = this->serverPort(); //测试代码 是否和上面的一样的Ip和port??? QString serverIp1 = serverSocket->localAddress().toString(); int serverPort1 = serverSocket->localPort(); //测试代码 switch (socketState) { case QAbstractSocket::UnconnectedState: qDebug() << "服务端:UnconnectedState:The socket is not connected."; //Global::systemLog->append(QString(tr("网络服务端状态:断开连接状态,未连上客户端Socket.客户端IP:%1")).arg(clientIp), QString(tr("与客户端计算机断开连接,客户端IP:%1,port:%2,UnconnectedState:The socket is not connected.")).arg(clientIp).arg(clientPort), SystemLog::INFO); break; case QAbstractSocket::HostLookupState: qDebug() << "服务端:HostLookupState:The socket is performing a host name lookup."; //Global::systemLog->append(QString(tr("网络服务端状态:正在查询计算机中......客户端IP:%1")).arg(clientIp), QString(tr("正在查询客户端计算机IP:%1,port:%2,HostLookupState:The socket is performing a host name lookup.")).arg(clientIp).arg(clientPort), SystemLog::INFO); break; case QAbstractSocket::ConnectingState: qDebug() << "服务端:ConnectingState:The socket has started establishing a connection."; //Global::systemLog->append(QString(tr("网络服务端状态:正在创建网络连接......客户端IP:%1")).arg(clientIp), QString(tr("正在创建网络连接,客户端计算机IP:%1,port:%2,ConnectingState:The socket has started establishing a connection.")).arg(clientIp).arg(clientPort), SystemLog::INFO); break; case QAbstractSocket::ConnectedState: qDebug() << "服务端:ConnectedState:A connection is established."; //Global::systemLog->append(QString(tr("网络服务端状态:TCP连接创建成功.客户端IP:%1")).arg(clientIp), QString(tr("网络已经连接成功,客户端计算机IP:%1,port:%2,ConnectedState:A connection is established.")).arg(clientIp).arg(clientPort), SystemLog::INFO); break; case QAbstractSocket::BoundState: qDebug() << "服务端:BoundState:The socket is bound to an address and port (for servers)."; //Global::systemLog->append(QString(tr("网络服务端状态:服务端已绑定TCP Socket.服务端IP:%1,port:%2.")).arg(serverIp).arg(serverPort), QString(tr("网络已经连接成功,本地服务端IP:%1,port:%2,客户端计算机IP:%3,port:%4,BoundState:The socket is bound to an address and port (for servers).")).arg(serverIp).arg(serverPort).arg(clientIp).arg(clientPort), SystemLog::INFO); break; case QAbstractSocket::ClosingState: qDebug() << "服务端:ClosingState:The socket is about to close (data may still be waiting to be written)."; //Global::systemLog->append(QString(tr("网络服务端状态:即将关闭一个TCP Socket.客户端IP:%1")).arg(clientIp), QString(tr("网络即将关闭,远程计算机IP:%1,port:%2,ClosingState:The socket is about to close (data may still be waiting to be written).")).arg(clientIp).arg(clientPort), SystemLog::INFO); break; case QAbstractSocket::ListeningState: qDebug() << "服务端:ListeningState:For internal use only."; //Global::systemLog->append(QString(tr("网络服务端状态:Socket侦听状态.客户端IP:%1")).arg(clientIp), QString(tr("网络侦听状态,远程计算机IP:%1,port:%2")).arg(clientIp).arg(clientPort), SystemLog::INFO); break; default: qDebug()<<"服务端:网络其他状态"; //Global::systemLog->append(QString(tr("网络服务端状态:其他状态.客户端IP:%1")).arg(clientIp), QString(tr("网络其他状态,远程计算机IP:%1,port:%2")).arg(clientIp).arg(clientPort), SystemLog::INFO); } serverSocket = 0; }
// This function assumes that the user wants to share his server while connected to // the Internet and that he/she is using direct access (eg no NATs). To determine the // IP we briefly connect to Hedgewars website and fallback to user intervention // after 4 seconds of timeout. void PageNetServer::copyUrl() { QString address = "hwplay://"; QTcpSocket socket; socket.connectToHost("www.hedgewars.org", 80); if (socket.waitForConnected(4000)) address += socket.localAddress().toString(); else address += "<" + tr("Insert your address here") + ">"; if (sbPort->value() != NETGAME_DEFAULT_PORT) address += ":" + QString::number(sbPort->value()); QClipboard *clipboard = HWApplication::clipboard(); clipboard->setText(address); qDebug() << address << "copied to clipboard"; }
void QxTransaction::executeClient(IxService * pService, const QString & sMethod) { if ((pService == NULL) || sMethod.isEmpty()) { qAssert(false); return; } if (pService->getServiceName().isEmpty()) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_NOT_SPECIFIED, "[QxOrm] empty service name")); return; } pService->registerClass(); QTcpSocket socket; QString serverName = QxConnect::getSingleton()->getIp(); long serverPort = QxConnect::getSingleton()->getPort(); socket.connectToHost(serverName, serverPort); if (! socket.waitForConnected(QxConnect::getSingleton()->getMaxWait())) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVER_NOT_FOUND, "[QxOrm] unable to connect to server")); return; } if (m_sTransactionId.isEmpty()) { setTransactionId(QUuid::createUuid().toString()); } setIpSource(socket.localAddress().toString()); setPortSource(socket.localPort()); setIpTarget(serverName); setPortTarget(serverPort); setServiceName(pService->getServiceName()); setServiceMethod(sMethod); setTransactionBegin(QDateTime::currentDateTime()); setInputParameter(pService->getInputParameter_BaseClass()); qx_bool bWriteOk = writeSocket(socket); if (! bWriteOk) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_WRITE_ERROR, QString("[QxOrm] unable to write request to socket : '") + bWriteOk.getDesc() + QString("'"))); return; } qx_bool bReadOk = readSocket(socket); if (! bReadOk) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_READ_ERROR, QString("[QxOrm] unable to read reply from socket : '") + bReadOk.getDesc() + QString("'"))); return; } pService->setOutputParameter(getOutputParameter()); pService->setMessageReturn(getMessageReturn()); setTransactionEnd(QDateTime::currentDateTime()); socket.disconnectFromHost(); if (socket.state() != QAbstractSocket::UnconnectedState) { socket.waitForDisconnected(QxConnect::getSingleton()->getMaxWait()); } }
const QByteArray Auth::calculateAuthKey() { QSqlDatabase db = QSqlDatabase::database ( m_db ); bool ok = false; QSqlQuery query(db); ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_SECRET'") ); if (!ok || !query.next()) { qDebug("Hash Error: error getting zm_auth_hash_secret from db %s", qPrintable(query.lastError().text())); return QByteArray(); } QString auth_key = query.value(0).toString(); // HASH Secret ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_IPS'") ); if (!ok || !query.next()) { qDebug("Hash Error: error getting zm_auth_hash_ips from db %s", qPrintable(query.lastError().text())); return QByteArray(); } bool use_remote_addr = query.value(0).toBool(); // Include remote addr? ok = query.exec( QString("SELECT now()") ); if (!ok || !query.next()) { qDebug("Hash Error: Can not read Server Time. now() function doesn't work %s", qPrintable(query.lastError().text())); return QByteArray(); } QDateTime dateTime = query.value(0).toDateTime(); auth_key += m_userName; auth_key += m_hashPassword; if ( use_remote_addr ) { QTcpSocket socket; socket.connectToHost( db.hostName(), ConnectionManager::connectionWebPort( m_db ), QIODevice::ReadOnly ); //if we can get ip address from the socket in 3000 ms if ( socket.waitForConnected( 3000 ) ){ auth_key += socket.localAddress().toString(); } else { //else try with HostInfo QHostInfo hinfo = QHostInfo::fromName ( QHostInfo::localHostName() ); QHostInfo checkLocalHost = QHostInfo::fromName ( db.hostName() ); if ( ! checkLocalHost.addresses().isEmpty() ) if ( checkLocalHost.addresses().first().toString() == "127.0.0.1" ) hinfo = checkLocalHost; if ( !hinfo.addresses().isEmpty() ) { //TODO: fix this. Use the correct interface address and not the first QHostAddress address = hinfo.addresses().first(); auth_key += address.toString(); } } } dateTime = dateTime.toTimeSpec( Qt::LocalTime ); auth_key += QString::number( dateTime.time().hour() ); //hour auth_key += QString::number( dateTime.date().day() ); //day of month auth_key += QString::number( dateTime.date().month() -1 ); //month auth_key += QString::number( dateTime.date().year() - 1900 ); //years since 1900 qDebug ( qPrintable("authkey: " + auth_key) ); QByteArray ret = QCryptographicHash::hash( auth_key.toUtf8(), QCryptographicHash::Md5 ); //qDebug ( qPrintable(QString (auth_key.toUtf8())) ); qDebug ( qPrintable("authkey hex: " + ret.toHex()) ); m_authKey = ret.toHex(); return m_authKey; }