예제 #1
0
void Server::recieveConnection()
{
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    QString client_ip = clientConnection->peerAddress().toString();
    quint32 client_ip_int = clientConnection->peerAddress().toIPv4Address();

    emit write_message(tr("New connection from IP: %1").arg(client_ip));

    if (sockets->contains(client_ip_int)) {
        QTcpSocket *oldClientConnection = (QTcpSocket*) sockets->value(client_ip_int);
        if (oldClientConnection && oldClientConnection->state() != QAbstractSocket::UnconnectedState) {
            oldClientConnection->disconnectFromHost();
        }
        sockets->remove(client_ip_int);
    }

    sockets->insert(client_ip_int, clientConnection);

    connect(clientConnection, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    connect(clientConnection, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(recieveData()));
    connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
예제 #2
0
void TCPSrc::onNewConnection()
{
	while(m_tcpServer->hasPendingConnections()) {
		QTcpSocket* connection = m_tcpServer->nextPendingConnection();
		connect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected()));

		switch(m_sampleFormat) {

			case FormatNFM:
			case FormatSSB: {
				quint32 id = (FormatSSB << 24) | m_nextSSBId;
				MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(true, id, connection->peerAddress(), connection->peerPort());
				m_nextSSBId = (m_nextSSBId + 1) & 0xffffff;
				m_ssbSockets.push_back(Socket(id, connection));
				msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI);
				break;
			}

			case FormatS16LE: {
				quint32 id = (FormatS16LE << 24) | m_nextS16leId;
				MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(true, id, connection->peerAddress(), connection->peerPort());
				m_nextS16leId = (m_nextS16leId + 1) & 0xffffff;
				m_s16leSockets.push_back(Socket(id, connection));
				msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI);
				break;
			}

			default:
				delete connection;
				break;
		}
	}
}
예제 #3
0
void Server::recieveConnection()
{
    if (is_init_connection) return;

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    QString client_ip = clientConnection->peerAddress().toString();
    quint32 client_ip_int = clientConnection->peerAddress().toIPv4Address();

    emit write_message(tr("New connection from IP: %1").arg(client_ip));

    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    if (client_ip_int == QHostAddress(remoteIPAddress).toIPv4Address() || is_config_mode) {
        if (remote_server_socket && clientConnection != remote_server_socket) {
            delete remote_server_socket;
        }
        remote_server_socket = clientConnection;
        connect(clientConnection, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
        connect(clientConnection, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
        connect(clientConnection, SIGNAL(readyRead()), this, SLOT(recieveData()));
        connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
    } else {
        clientConnection->abort();
    }
}
예제 #4
0
void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket *localSocket = new QTcpSocket;
    localSocket->setSocketDescriptor(socketDescriptor);

    if (!isLocal && autoBan && Common::isAddressBanned(localSocket->peerAddress())) {
        emit debug(QString("A banned IP %1 attempted to access this server")
                   .arg(localSocket->peerAddress().toString()));
        localSocket->deleteLater();
        return;
    }

    //timeout * 1000: convert sec to msec
    TcpRelay *con = new TcpRelay(localSocket,
                                 timeout * 1000,
                                 serverAddress,
                                 ep,
                                 isLocal,
                                 autoBan,
                                 auth);
    conList.append(con);
    connect(con, &TcpRelay::info, this, &TcpServer::info);
    connect(con, &TcpRelay::debug, this, &TcpServer::debug);
    connect(con, &TcpRelay::bytesRead, this, &TcpServer::bytesRead);
    connect(con, &TcpRelay::bytesSend, this, &TcpServer::bytesSend);
    connect(con, &TcpRelay::latencyAvailable,
            this, &TcpServer::latencyAvailable);
    connect(con, &TcpRelay::finished, this, [=]() {
        if (conList.removeOne(con)) {
            con->deleteLater();
        }
    });
    con->moveToThread(threadList.at(workerThreadID++));
    workerThreadID %= totalWorkers;
}
예제 #5
0
void NetMaster::handleDisconnection()
{
    QTcpSocket * socket = (QTcpSocket*)sender();
    m_sockets.removeAll(socket);
    m_connectedClients.removeRow(m_connectedClients.match(
        m_connectedClients.index(0, 0),
        Qt::DisplayRole,
        socket->peerAddress().toString()).at(0).row());

    qDebug() << "Slave disconnected from" << socket->peerAddress().toString();
}
예제 #6
0
void Server::slotNewConnection()
{
	QTcpSocket* pClientSocket = ptcpServer->nextPendingConnection();
	connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
	connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()));
	QString str = "Server Response: Connected!!";
	QString* pstr = &str;
	sendToClient(pClientSocket, *pstr);
	QString buf = "New client connected: Новий клієнт" + pClientSocket->peerAddress().toString();
	emit signal_display(buf);
	clients.insert(pClientSocket->peerAddress().toString(), pClientSocket);
}
예제 #7
0
void NetMaster::handleConnection()
{
    QTcpSocket * socket = m_server->nextPendingConnection();
    connect(socket, SIGNAL(disconnected()), this, SLOT(handleDisconnection()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(dataReady()));
    m_sockets.append(socket);
    m_connectedClients.appendRow(new QStandardItem(socket->peerAddress().toString()));

    qDebug() << "New connection from" << socket->peerAddress().toString();

    // Send initial packets:
    
    NetPacket("INIT_DONE").writeOut(socket);
}
예제 #8
0
void Server::sendResponse() {
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    stringstream peerStream;
    peerStream << clientConnection->peerAddress().toString().toStdString()
            << ":"
            << clientConnection->peerPort();
    string peer = peerStream.str();

    if (clientConnection->waitForReadyRead(10000)) {
        clientConnection->readLine(readBuffer, BUFFER_LEN);
        string message(readBuffer);
        string deviceId = "";

        if (message.length() > 4) {
            deviceId = message.substr(4);
        }

        if (message.find("GET ", 0, 4) == 0) {
            string response = processGetOpertion(peer, deviceId);
            clientConnection->write(response.c_str());
        } else if (message.find("ADD ", 0, 4) == 0) {
            bool added = processAddOpertion(deviceId);
            if (added) {
                clientConnection->write("ADDED");
            } else {
                clientConnection->write("NOT ADDED");
            }
        }
    }
    clientConnection->disconnectFromHost();
}
예제 #9
0
파일: server.cpp 프로젝트: otri/vive
/* perform the operations for a frame:
 *   - check to see if the connections are still alive (checkAlive)
 *      - this will emit connectionsChanged if there is a any change in the connection status
 *   - grab a text stream of the current model data ( stream << *subjectList )
 *   - put the text stream on the wire s->write(...)
*/
void MyServer::process()
{
    stopProfile("Other");

    working = true;

    startProfile("checkAlive");
    int alive = checkAlive();
    stopProfile("checkAlive");

    if(alive > 0)
    {
        startProfile("Serve");

        count++;
        QString buffer;
        QTextStream stream(&buffer);
        // The following operation is threadsafe.
        startProfile("Fetch");
        subjectList->read(stream, true);
        stopProfile("Fetch");

        startProfile("Wait");
        listMutex.lock();
        stopProfile("Wait");

        // for each connection
        for(QList<ServerConnection *>::iterator i =  connections.begin(); i != connections.end(); i++)
        {
            QTcpSocket *s = (*i)->socket;
            if(s->state() != QAbstractSocket::ConnectedState) continue;

            QString d = QString("%1\nEND\r\n").arg(buffer);

            startProfile("Write");
            int written = s->write(d.toUtf8());
            stopProfile("Write");

            if(written == -1)
            {
                emit outMessage(QString(" Error writing to %1").arg(s->peerAddress().toString()));
            }
            else
            {
                s->flush();
            }
        }

        listMutex.unlock();

        stopProfile("Serve");
    }

    working = false;


    startProfile("Other");


}
예제 #10
0
void ServerSktTcp::newConnection()
{
	QTcpServer* server = qobject_cast<QTcpServer*>(sender());
	if (!server) return;

	QTcpSocket* client = server->nextPendingConnection();
	while (client)
	{
		Conn* conn = new Conn;
		if (!conn)
		{
			client->deleteLater();
		}
		else
		{
			client->setProperty(PROP_CONN, qVariantFromValue((void*)conn));

			conn->client = client;
			conn->key = TK::ipstr(client->peerAddress(),client->peerPort(), true);

			connect(client, SIGNAL(readyRead()), this, SLOT(newData()));
			connect(client, SIGNAL(destroyed(QObject*)), this, SLOT(close(QObject*)));
			connect(client, SIGNAL(disconnected()), client, SLOT(deleteLater()));
			connect(client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error()));

			setCookie(conn->key, conn);
		}
		client = server->nextPendingConnection();
	}
}
예제 #11
0
/**
  This method will be invoked by Qt framework when a client connection gets 
  disconnected.
*
@param: none
*
@return: none
*******************************************************************************/
void CuteHttpServer::removeClosedConn()
{
    // who sent the Qt signal?
    QTcpSocket* caller = dynamic_cast<QTcpSocket*>(sender());
    
    vector<QTcpSocket*>::iterator iter;
    QTcpSocket* conn = 0;

    if(caller == 0)
    {
        // 1. invoked by Qt on shutdown!
        //  -- find first closing conn:
        for(iter = m_connections.begin(); iter != m_connections.end(); iter++)
        {
            // empty slot?
            if(*iter == 0) continue;

            if((*iter)->state() == QAbstractSocket::UnconnectedState)
            {
                conn = *iter;
                break;
            }
        }
    }
    else
    {
        // 2. normal case, client exited, TCP object called back
        iter = find(m_connections.begin(), m_connections.end(), caller);

        if(iter != m_connections.end())
        {
            conn = *iter;
            assert(conn == caller);
        }
    }       

    // found?    
    if(conn != 0)
    {
        assert(iter != m_connections.end());    
        int connID = delSavedConn(conn);

        //delete conn; --> NO-GO!, Qt will need it later in this event handler!
        conn->deleteLater();  // Qt will delte it!        

        if(TR_WEBIF || INFO_LVL)
        {
            TRACE_INFO3("http_srv: client conn closed, connection's IpAddr/clientId=", 
                        conn->peerAddress().toString(), connID);
            if(TR_WEBIF) TRACE2("http_srv: opened conns=", m_connCount);
        }

        // reset request's references:
        for_each(m_requests.begin(), m_requests.end(), ResetConnIdIf(connID));      
    }
    else
    {
        TRACE_ERR("http_srv: conn. closing signalled but no closed conn. found!");
    }        
}
예제 #12
0
void ListenRISRequests::newRISRequest()
{
    QTcpSocket *tcpSocket = m_tcpRISServer->nextPendingConnection();
    QString risRequestData;

    INFO_LOG("Rebuda peticio de la IP " + tcpSocket->peerAddress().toString());
    if (tcpSocket->waitForReadyRead(TimeOutToReadData))
    {
        risRequestData = QString(tcpSocket->readAll());
        INFO_LOG("Dades rebudes: " + risRequestData);
    }
    else
    {
        INFO_LOG("No s'ha rebut dades, error: " + tcpSocket->errorString());
    }

    INFO_LOG("Tanco socket");
    tcpSocket->disconnectFromHost();
    INFO_LOG("Faig delete del socket");
    delete tcpSocket;

    if (!risRequestData.isEmpty())
    {
        processRequest(risRequestData);
    }
}
예제 #13
0
void MrimConnection::connected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);
	SystemIntegration::keepAlive(socket);

    bool connected = false;

    switch (socket->state())
    {
    case QAbstractSocket::ConnectedState:
        connected = true;
        break;
    default:
        break;
    }

    QString address = Utils::toHostPortPair(socket->peerAddress(),socket->peerPort());

    if (!connected)
    {
        debug()<<"Connection to server"<<qPrintable(address)<<"failed! :(";
        return;
    }
    else
    {
        debug()<<"Connected to server"<<qPrintable(address);

        if (socket == p->IMSocket()) //temp
        {
            sendGreetings();
        }
    }
}
예제 #14
0
void ServerCore::processDeviceCommandSocket()
{
	if (!serverStart)
	{
		return;
	}

	QTcpSocket *socket = deviceCmdServer->nextPendingConnection();

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		QVariantMap retParamMap = prepareDataForDevice(jsonObj);
		TCP_REPLY_TYPE retType = (TCP_REPLY_TYPE)retParamMap[JSON_KEY_RETURN_TYPE].toInt();

		QString retString = JsonGenerator::GenerateJsonReply(retType, retParamMap);
		QString peerAddress = socket->peerAddress().toString();
		socket->write(retString.toLatin1());

		bool isSuccess = socket->waitForBytesWritten();

		Q_EMIT dataWrittenToDevice(peerAddress, retString);

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});
}
예제 #15
0
void MessageDispatcherThread::run()
{
    QTcpSocket socket;
    socket.setSocketDescriptor(m_descriptor);
    quint64 dataSize = 0;

    while(!m_doQuit)
    {
        socket.waitForReadyRead();

        if (dataSize == 0) {
            QDataStream stream(&socket);
            stream.setVersion(QDataStream::Qt_4_6);

            if (socket.bytesAvailable() < sizeof(quint64))
                continue;

            stream >> dataSize;
        }

        if (socket.bytesAvailable() < dataSize)
            continue;

        emit gotMessage(socket.readAll(), socket.peerAddress());
        break;
    }
예제 #16
0
void            HostedCall::receiveNewTcpConnection()
{
    int             id;
    bool            ok = false;
    QTcpSocket      *sock = this->_tcpServer.nextPendingConnection();
    if (sock != 0)
    {
        std::cout << "Receive new tcp connection" << std::endl;
        QString ip = sock->peerAddress().toString();
        QList<Callee>::iterator it = this->_allowedUser.begin();
        for (; it != this->_allowedUser.end(); ++it)
        {
            if (it->getIp() == ip)
            {
                ok = true;
                it->setSock(sock);
                connect(sock, SIGNAL(readyRead()), &this->_worker, SLOT(onReadSomething()));
                connect(sock, SIGNAL(disconnected()), &this->_worker, SLOT(onClientDisconnectedFromCall()));
                connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
                id = this->_connectedUsers.count() + 1;
                this->_container.addProducer(id);
                this->sendWelcome(id, sock);
                this->sendParticipantStatusUpdate(true, id, it->getUsername());
                this->sendUdpReady(sock);
                this->_connectedUsers[id] = Callee(it->getIp(), it->getUsername());
                this->_connectedUsers[id].setSock(sock);
                this->_allowedUser.erase(it);
                break;
            }
        }
        if (!ok)
            sock->close();
    }
}
예제 #17
0
/**
 * Slot
 * @brief Serveur::pretALire
 */
void Serveur::readyRead()
{
    QTcpSocket *client = (QTcpSocket*)sender();
    while(client->canReadLine())
    {
        QString ligne = QString::fromUtf8(client->readLine()).trimmed();
        qDebug() << "Read line:" << ligne;

        QRegExp meRegex("^/me:(.*)$");

        if(meRegex.indexIn(ligne) != -1)
        {
            QString utilisateur = meRegex.cap(1);
            m_utilisateurs[client] = utilisateur;
            foreach(QTcpSocket *client, m_clients)
                client->write(QString("Serveur:" + utilisateur + " a rejoint le serveur.\n").toUtf8());
            envoyerListeUtilisateur();
        }
        else if(m_utilisateurs.contains(client))
        {
            QString message = ligne;
            QString utilisateur = m_utilisateurs[client];
            qDebug() << "Utilisateur:" << utilisateur;
            qDebug() << "Message:" << message;

            foreach(QTcpSocket *otherClient, m_clients)
                otherClient->write(QString(utilisateur + ":" + message + "\n").toUtf8());
        }
        else
        {
            qWarning() << "Erreur du client:" << client->peerAddress().toString() << ligne;
        }
    }
}
void lc::ClientHelpNotificationServer::SendReply() {
    QByteArray block;
    QDataStream out{ &block, QIODevice::WriteOnly };
    out.setVersion( QDataStream::Qt_5_2 );
    out << ( quint16 )0;
    out << QString{ "Help demand retrieved." };
    out.device()->seek( 0 );
    out << ( quint16 )( block.size() - sizeof( quint16 ) );

    QTcpSocket *clientConnection = helpMessageServer->nextPendingConnection();
    QString peerAddress = clientConnection->peerAddress().toString();
    QString peerName;
    bool unknownClient = false;
    if ( settings->clIPsToClMap.contains( peerAddress ) ) {
        peerName = settings->clIPsToClMap[ peerAddress ]->name;
    } else {
        unknownClient = true;
    }

    connect( clientConnection, &QTcpSocket::disconnected, clientConnection, &QTcpSocket::deleteLater );
    clientConnection->write( block );
    clientConnection->disconnectFromHost();

    if ( unknownClient ) {
        QMessageBox requestReceivedBox{ QMessageBox::Information, tr( "Unknown client asked for help."),
                    tr( "An unknown client with IP '%1' asked for help.").arg( peerAddress ), QMessageBox::Ok };
        requestReceivedBox.exec();
    } else {
        QMessageBox requestReceivedBox{ QMessageBox::Information, tr( "'%1' asked for help.").arg( peerName ),
                    tr( "'%1' asked for help.").arg( peerName ), QMessageBox::Ok };
        requestReceivedBox.exec();
    }
}
예제 #19
0
void brain_stroke_server::deal_next_request(){
    puts("deal next");
    //get next request
    deque_mutex.lock();
    if(request_list.size() != 0){
        puts("has next");
        QTcpSocket * client = request_list.front();
        request_list.pop_front();
        deque_mutex.unlock();
        //ignore closing socket
        if(client->state() == QTcpSocket::UnconnectedState || client->state() == QTcpSocket::ClosingState){
            client->close();
            QLOG_DEBUG() << "close client" << client;
            std::cout << "close client:" << client->peerAddress().toString().toStdString() << std::endl;
            //search next from request_list
            deal_next_request();
            return;
        }
        tcp_deal * tcp_deal_thread = new tcp_deal();
        tcp_deal_thread -> set_socket(client);
        connect(tcp_deal_thread, SIGNAL(finished()), this, SLOT(deal_next_request()));
        connect(tcp_deal_thread, SIGNAL(finished()), tcp_deal_thread, SLOT(deleteLater()));
        tcp_deal_thread -> start();
        return;
    }
    deque_mutex.unlock();
    QMutexLocker calculate_flag_mutex_locker(&calculate_flag_mutex);
    //no calculating now
    calculate_flag = false;
    return;
}
예제 #20
0
void HttpSocket::handleNewConnection()
{
    DBUG;
    while (hasPendingConnections()) {
        QTcpSocket *socket = nextPendingConnection();

        // prevent clients from sending too much data
        socket->setReadBufferSize(constMaxBuffer);

        static const QLatin1String constIpV6Prefix("::ffff:");

        QString peer=socket->peerAddress().toString();
        QString ifaceAddress=serverAddress().toString();
        const bool hostOk=peer==ifaceAddress || peer==mpdAddr || peer==(constIpV6Prefix+mpdAddr) ||
                          peer==QLatin1String("127.0.0.1") || peer==(constIpV6Prefix+QLatin1String("127.0.0.1"));

        DBUG << "peer:" << peer << "mpd:" << mpdAddr << "iface:" << ifaceAddress << "ok:" << hostOk;
        if (!hostOk) {
            sendErrorResponse(socket, 400);
            socket->close();
            DBUG << "Not from valid host";
            return;
        }

        connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
    }
}
예제 #21
0
/**
 * @brief Accept or reject new client connection
 */
void BuiltinServer::newClient()
{
	QTcpSocket *socket = _server->nextPendingConnection();

	logger::info() << "Accepted new client from address" << socket->peerAddress();

	_sessions->addClient(new Client(socket));
}
예제 #22
0
/**
 * @brief Accept or reject new client connection
 */
void BuiltinServer::newClient()
{
	QTcpSocket *socket = m_server->nextPendingConnection();

	qInfo("Accepted new client from address %s", qPrintable(socket->peerAddress().toString()));

	m_sessions->addClient(new Client(socket, m_sessions->config()->logger()));
}
예제 #23
0
void Server::onClientConnected()
{
    QTcpSocket *clientSocket = m_server->nextPendingConnection();

    RemoteClient *client = new RemoteClient(clientSocket, this);

    m_clients << client;

    client->setNickname(clientSocket->peerAddress().toString());

    for (RemoteClient *client : m_clients) {
        client->sendMessage("client connect" + clientSocket->peerAddress().toString());
    }

    connect(client,SIGNAL(messageReceived(QString)),
            this,SLOT(onClientMessageReceived(QString)));
}
예제 #24
0
void TvEventHandler::incomingConnection(qintptr socket)
{
    QTcpSocket* tcpSocket = new QTcpSocket(this);
    tcpSocket->setSocketDescriptor(socket);
    qCDebug(dcLgSmartTv) << "Event handler -> incoming connection" << tcpSocket->peerAddress().toString() << tcpSocket->peerName();

    connect(tcpSocket, &QTcpSocket::readyRead, this, &TvEventHandler::readClient);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &TvEventHandler::onDisconnected);
}
예제 #25
0
/**
 * @brief Accept or reject new client connection
 */
void MultiServer::newClient()
{
	QTcpSocket *socket = _server->nextPendingConnection();

	logger::info() << "Accepted new client from address" << socket->peerAddress();

	auto *client = new Client(socket);
	_sessions->addClient(client);

	if(_banlist) {
		if(_banlist->isBanned(socket->peerAddress())) {
			logger::info() << "Kicking banned client from address" << socket->peerAddress() << "straight away";
			client->disconnectKick("BANNED");
		}
	}

	printStatusUpdate();
}
void DataTransferServer::incomingConnection(int socketfd)
{
    QTcpSocket *client = new QTcpSocket(this);
    client->setSocketDescriptor(socketfd);
    clients.insert(client);
     qDebug() << "New client from:" << client->peerAddress().toString();
    connect(client, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
}
예제 #27
0
void Display::newConnection()
{
    qDebug() << "Woot woot actually connected";
    qDebug() << "lol jk m8 nothing works at all";
    QTcpSocket *socket = server->nextPendingConnection();
    qDebug() << socket->peerAddress();
    connect(socket, SIGNAL(readyRead()),
    this, SLOT(read_msg()));
}
예제 #28
0
// Richiesta connessione TCP in ingresso
void DuktoProtocol::newIncomingConnection()
{

    // Verifica presenza connessione pendente
    if (!mTcpServer->hasPendingConnections()) return;

    // Recupero connessione
    QTcpSocket *s = mTcpServer->nextPendingConnection();

    // Se sto già ricevendo o inviando, rifiuto la connessione
    if (mIsReceiving || mIsSending)
    {
        s->close();
        return;
    }

    // Aggiornamento interfaccia grafica
    receiveFileStart(s->peerAddress().toString());

    // Impostazione socket TCP corrente
    mCurrentSocket = s;

    // Attesa header della connessione (timeout 10 sec)
    if (!s->waitForReadyRead(10000))
    {
        // Non ho ricevuto l'header della connessione, chiudo
        mCurrentSocket->close();
        delete mCurrentSocket;
        mCurrentSocket = NULL;
        return;
    }

    // Registrazione gestori eventi socket
    connect(mCurrentSocket, SIGNAL(readyRead()), this, SLOT(readNewData()), Qt::DirectConnection);
    connect(mCurrentSocket, SIGNAL(disconnected()), this, SLOT(closedConnectionTmp()), Qt::QueuedConnection);

    // Inizializzazione variabili
    mIsReceiving = true;
    mTotalReceivedData = 0;
    mElementSize = -1;
    mReceivedFiles = new QStringList();
    mRootFolderName = "";
    mRootFolderRenamed = "";
    mReceivingText = false;
    mRecvStatus = FILENAME;

    // -- Lettura header generale --
    // Numero entità da ricevere
    mCurrentSocket->read((char*) &mElementsToReceiveCount, sizeof(qint64));
    // Dimensione totale
    mCurrentSocket->read((char*) &mTotalSize, sizeof(qint64));

    // Inizio lettura dati sui file
    readNewData();

}
예제 #29
0
void ChatServer::serverGotNewConnection()
//activates when server got new incoming connection
//isn't very important for us, cause server requires authorization
//so we still waiting authorization/registration request from that son of a bitch
{
    QTcpSocket *newSocket = m_tcpServer->nextPendingConnection();
    connect(newSocket, SIGNAL(readyRead()), this, SLOT(serverGotNewMessage()));
    QString log = "Server got new connection from " + newSocket->peerAddress().toString() + ":" + QString::number(newSocket->peerPort());
    emit serverLog(esNotify, log);
}
예제 #30
0
void ChatServer::socketDisconnected()
{
    qDebug() << "socket disconnected";
    QTcpSocket *senderSocket = qobject_cast<QTcpSocket *>(sender());
    QString address = senderSocket->peerAddress().toString();
    quint16 port = senderSocket->peerPort();

    m_socketList.removeAll(senderSocket);
    emit disconnected(address, port);
}