Esempio n. 1
0
/* service traffic from clients and drivers */
static void
indiRun(void)
{
	fd_set rs;
	int maxfd;
	int i, s;

	/* start with public contact point */
	FD_ZERO(&rs);
	FD_SET(lsocket, &rs);
	maxfd = lsocket;

	/* add all client and driver read fd's */
	for (i = 0; i < nclinfo; i++) {
	    ClInfo *cp = &clinfo[i];
	    if (cp->active) {
		FD_SET(cp->s, &rs);
		if (cp->s > maxfd)
		    maxfd = cp->s;
	    }
	}
	for (i = 0; i < ndvrinfo; i++) {
	    DvrInfo *dp = &dvrinfo[i];
	    FD_SET(dp->rfd, &rs);
	    if (dp->rfd > maxfd)
		maxfd = dp->rfd;
	}

	/* wait for action */
	s = select (maxfd+1, &rs, NULL, NULL, NULL);
	if (s < 0) {
	    fprintf (stderr, "%s: select(%d): %s\n",me,maxfd+1,strerror(errno));
	    exit(1);
	}

	/* new client? */
	if (s > 0 && FD_ISSET(lsocket, &rs)) {
	    newClient();
	    s -= 1;
	}

	/* message from client? */
	for (i = 0; s > 0 && i < nclinfo; i++) {
	    if (clinfo[i].active && FD_ISSET(clinfo[i].s, &rs)) {
		clientMsg(&clinfo[i]);
		s -= 1;
	    }
	}

	/* message from driver? */
	for (i = 0; s > 0 && i < ndvrinfo; i++) {
	    if (FD_ISSET(dvrinfo[i].rfd, &rs)) {
		driverMsg(&dvrinfo[i]);
		s -= 1;
	    }
	}
}
Esempio n. 2
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    curSocket(NULL), connectSocket(NULL)
{
    ui->setupUi(this);
    ui->plainTextEdit->appendPlainText(tr("begin listen 13334 %1").arg(tcpServer.listen(QHostAddress::Any, 7777)));
    connect(&tcpServer, SIGNAL(newConnection()), this, SLOT(newClient()));
}
void serverStateClass::waitConnection()
{
    std::unique_ptr<client> newClient(new client);
    sf::Socket::Status stat = listener.accept(newClient->socket);
    if(stat == sf::Socket::Done)
    {
        sf::Packet packet;
        sf::Packet packetForMap;
        sf::Packet packetMoveTotal;
        sf::Packet packetMoveNumber;
        packet << static_cast<sf::Uint8>(YOU_ARE);
        newClient->socket.setBlocking(false);
        selector.add(newClient->socket);
        newClient->player = NO_PLAYER;
        playerReady = true;
        ++numberOfSpectator;
        for(int i = 0; i < server.getTotalPlayer(); ++i)
        {
            if(playerIsReady[i] == false)
            {
                if(newClient->player == NO_PLAYER)
                {
                    playerIsReady[i] = true;
                    newClient->player = static_cast<typePlayer>(i);
                    --numberOfSpectator;
                    ++numberOfPlayer;
                }
                else
                {
                    playerReady = false;
                }
            }
        }

        packetMoveTotal << static_cast<sf::Uint8>(SET_MOVE_TOTAL);
        packetMoveTotal << static_cast<sf::Uint8>(numberMoveTotal);
        packetMoveNumber << static_cast<sf::Uint8>(SET_MOVE_NUMBER);
        packetMoveNumber << static_cast<sf::Uint8>(numberMoveNumber);

        nbPlayer->setMessage(intToStr(numberOfPlayer));
        nbSpec->setMessage(intToStr(numberOfSpectator));
        myWidgetManager.widgetHasChanged();

        packet << static_cast<sf::Uint8>(newClient->player);
        packetForMap = server.getPacketForMap();

        listClientMainThread.push_back(std::make_shared<client>());
        listClientMainThread.back().reset(newClient.release());
        listClientSendThread.push_back(listClientMainThread.back());
        listClientReceiveThread.push_back(listClientMainThread.back());
        addNewPacket(packet, *listClientMainThread.back());
        addNewPacket(packetForMap, *listClientMainThread.back());
        addNewPacket(packetMoveTotal, *listClientMainThread.back());
        addNewPacket(packetMoveNumber, *listClientMainThread.back());
    }
}
Esempio n. 4
0
/**
 * return: >0 OK, else failed,will close socket.
 */
int doNewClientIn(int sockfd){
    struct _client *thisClient = newClient(sockfd);
    if(thisClient == 0 ){
        close(sockfd);
        return getErr();
    }
    //thisClient->sendCommand(thisClient,CMD_GET_ID,0,0);
    clientGetIdFromBoard(thisClient);
    return sockfd;
}
Esempio n. 5
0
void Server::acceptClientConnection()
{
	QTcpSocket* clientSocket = mTcpServer->nextPendingConnection();
	emit newClient(clientSocket->peerAddress().toString());
	int idusersocs = clientSocket->socketDescriptor();
	mSClients[idusersocs] = clientSocket;
	connect(mSClients[idusersocs], SIGNAL(disconnected()), mIPAddressMapper, SLOT(map()));
	mIPAddressMapper->setMapping(mSClients[idusersocs], mSClients[idusersocs]->peerAddress().toString());
	connect(mSClients[idusersocs], SIGNAL(disconnected()), mSClients[idusersocs], SLOT(deleteLater()));
	sendSettings();
}
Esempio n. 6
0
void Network::launch()
{
    if (server->listen(QHostAddress::Any, settings->value(AreaString::portValue).toInt()))
    {
        Utils::printConsole(AreaString::launchSuccessMessage.arg(QDateTime::currentDateTime().toString(AreaString::dateFormat)));
        log->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append);
        connect(server, SIGNAL(newConnection()), this, SLOT(newClient()));
    }
    else
    {
        Utils::printConsole(AreaString::launchFailureMessage);
        exit(EXIT_FAILURE);
    }
}
Esempio n. 7
0
void Connection::processData()
{
    m_buffer = read(m_numBytesForCurrentDataType);
    if(m_buffer.size() != m_numBytesForCurrentDataType) {
        abort();
        return;
    }

    switch(m_currentDataType) {
    case Greeting:
        if(m_identity == PrimaryServer || m_identity == BackupServer) {
            emit newClient(this);
        } else if(m_identity == Client) {
            emit newGreeting(m_buffer);
        }
        break;
    case Direction:
        if(m_identity == PrimaryServer || m_identity == BackupServer) {
            emit newMove(m_buffer);
        }
        break;
    case GameState:
        if(m_identity == BackupServer || m_identity == Client) {
            emit newState(m_buffer);
        }
        break;
    case SelectServer:
        if(m_identity == Client) {
            emit newBackupServer(m_buffer);
        }
        break;
    case Acknowledge:
        if(m_identity == PrimaryServer) {
            emit newAck();
        }
        break;
    case PlayerAddr:
        if(m_identity == BackupServer) {
            emit newPlayerAddr(m_buffer);
        }
        break;
    default:
        break;
    }

    m_currentDataType = Undefined;
    m_numBytesForCurrentDataType = 0;
    m_buffer.clear();
}
Esempio n. 8
0
void releaseBlockLocks(char* serviceName, int servicePort,
                       char* fileName, int lockID) {

    MessageClient client = newClient(serviceName, servicePort);
    Message m = newMessage();
    m->type = FILE_LOCK_CLIENT_SERVICE_CLIENT_MESSAGE;
    setStringParam(m, "functionName", "releaseblock");
    setStringParam(m, "fileName", fileName);
    setIntegerParam(m, "lockID", lockID);
    Message reply = clientCall(client, m);
    clientDisconnect(client);
    
    destroyMessage(m);
    destroyMessage(reply);
}
Esempio n. 9
0
void getOnlineList(DATA *data){
	int i;
	for(i=0;i<10;i++){
		if(peers[i]!=NULL){
			addClient(data, newClient(
					peers[i]->name,
					peers[i]->ip,
					peers[i]->port,
					peers[i]->nameLen
				));
			data->length += peers[i]->nameLen;
			data->length += (4+4+2);
		}
	}
}
Esempio n. 10
0
bool MultiServer::createServer()
{
	if(!_sslCertFile.isEmpty() && !_sslKeyFile.isEmpty()) {
		SslServer *server = new SslServer(_sslCertFile, _sslKeyFile, this);
		if(!server->isValidCert())
			return false;
		_server = server;

	} else {
		_server = new QTcpServer(this);
	}

	connect(_server, SIGNAL(newConnection()), this, SLOT(newClient()));

	return true;
}
Esempio n. 11
0
void acceptNewClient(int serverSocket)
{
	struct sockaddr_in newClientAddress;
	socklen_t sockLength = sizeof(newClientAddress);
	struct ClientNode *client =  newClient();

	if ((client->clientSocket = accept(serverSocket, (struct sockaddr *) &newClientAddress, &sockLength)) < 0) {
		perror("acceptNewClient:accept");
		free(client);
		return;
	}

	if (clientList->maxSocket < client->clientSocket) {
		clientList->maxSocket = client->clientSocket;
	}
}
Esempio n. 12
0
File: serveur.cpp Progetto: Ooya/tp3
serveur::serveur()
{
    this->server = new QTcpServer();

    if (!server->listen(QHostAddress::LocalHost, 4444)) {
        qDebug() << "impossible de lancer le serveur";
        return;
    }
    QString ipAddress;
    ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    qDebug() << "address = " << server->serverAddress() << "\nport = " << server->serverPort();
    connect(server, SIGNAL(newConnection()), this, SLOT(newClient()));

    this->time = new QTimer();
    time->start(10000);
    connect(time,SIGNAL(timeout()),this,SLOT(emitSeason()));
}
Esempio n. 13
0
std::shared_ptr<Client> ClientController::CreateClient(const Client &client)
{
    if(!(UserSingleton::GetInstance().GetPermissions() & PLM::PermissionsFlag::WRITE_CLIENTS))
    {
        return std::shared_ptr<Client>();
    }

    std::unique_ptr<Client> newClient(new Client());
    CopyContactData(client, *newClient);

    if(!CreateContact(*newClient))
    {
        return std::shared_ptr<Client>();
    }

    QSqlQuery query = GetDb().CreateQuery();
    query.prepare("INSERT INTO \"Client\" "
        "("
        "\"ContactId\", "
        "\"CompanyName\""
        ") "
        "VALUES"
        "("
        ":contactId, "
        ":companyName"
        ")"
        " RETURNING \"ClientId\";"
    );

    query.bindValue(":companyName", newClient->GetAccountName());
    query.bindValue(":contactId", newClient->GetId());

    if(!query.exec())
    {
        return std::shared_ptr<Client>();
    }

    query.next();
    qint32 clientId = query.value("ClientId").toInt();
    newClient->SetClientId(clientId);

    auto sharedPtr = AddClient(std::move(newClient));
    emit sigClientAdded(*sharedPtr);
    return sharedPtr;
}
Esempio n. 14
0
Inverter::Inverter(bool output)
    : m_stdout(output), m_cycle(MSG_DETAIL)
{
    // set up our UDP socket
    // this is used to find all inverters on the LAN
    m_udpsocket = new QUdpSocket(this);

    // setup our tcp server
    // this is used to send control messages to any inverters that respond to UDP messages
    m_server    = new QTcpServer(this);

    // start the TCP server and listen on the standard samil port
    connect(m_server, SIGNAL(newConnection()),this, SLOT(newClient()));
    m_server->listen(QHostAddress::Any, TCP_PORT);

    // start a new timer that will send out UDP discovery messages on timeout
    connect(&m_connectTimer, SIGNAL(timeout()), this, SLOT(doConnect()));
    m_connectTimer.start(CONNECTION_TIME);

}
Esempio n. 15
0
LogHandler::~LogHandler()
{
    if (m_localSocket != nullptr) {
        QString msg = " Shutdown log client, instance name: " + m_instName;
        localLogProc(1, msg);
    }
    if (m_localServer != nullptr) {
        QString msg = " Shutdown log server, instance name: " + m_instName;
        localLogProc(1, msg);
    }

    // reward all local msg to the function
    qInstallMessageHandler(nullptr);

    if (m_localSocket != nullptr)
    {
        disconnect(m_localSocket, SIGNAL(disconnected()), this, SLOT(svrClose()));
        m_localSocket->disconnectFromServer();
        if (!m_localSocket->waitForDisconnected(500))
            m_localSocket->abort();
        m_localSocket->deleteLater();
        m_localSocket = nullptr;
    }

    // delete server
    if (m_localServer != nullptr)
    {
        if (m_localServer->isListening())
            disconnect(m_localServer, SIGNAL(newConnection()), this, SLOT(newClient()));
        m_localServer->deleteLater();
        m_localServer = nullptr;
    }

    if (m_pFile != nullptr)
    {
        m_pFile->flush();
        m_pFile->close();
        m_pFile->deleteLater();
        m_pFile = nullptr;
    }
}
Esempio n. 16
0
    /**
      * Appelé quand un client se connecte au serveur.
      * Envoie la connexion au serveur si celle-ci
      * n'est pas filtrée
      */
    void ClientHandler::handleIncomming()
    {
        //On recupère le socket server
        QTcpServer *server = qobject_cast<QTcpServer*>(sender());
        //Si ce n'est pas un socket qui a envoyé
        if (server == NULL)
        {
            qDebug() << "ClientHandler::handleIncomming: Erreur, socket serveur incorrect";
            return;
        }
        //On recupère la socket
        QTcpSocket *socket = server->nextPendingConnection();
        //Si la socket n'existe pas, on retourne
        if (socket == NULL)
        {
            return;
        }
        //On indique qu'un client s'est connecté.
        qDebug() << "Nouvelle connexion en provenance de " << socket->peerAddress().toString();
        //Sinon, on procède à des vérifications

        //On vérifie que le nombre maximal de joueurs n'est pas atteint
        if (getClientsOnline() >= _maxPlayers)
        {
            //On affiche un message dans la console
            qDebug() << "Trop de joueurs dans le serveur.";
            //On deconnecte le client
            socket->close();

            return;
        }
        //TODO: Programmer la véfification du client.

        //On connecte le signal pour la deconnexion
        connect(socket,SIGNAL(disconnected()),this,SLOT(handleDisconnection()));
        //On envoie le signal pour dire qu'il y'a un nouveau client
        emit newClient(socket);
    }
/**
 * Handle incoming Connection Request
 */
void WebSocketsServer::handleNewClients(void) {

#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
    while(_server->hasClient()) {
#endif
        bool ok = false;

#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
        // store new connection
        WEBSOCKETS_NETWORK_CLASS * tcpClient = new WEBSOCKETS_NETWORK_CLASS(_server->available());
#else
        WEBSOCKETS_NETWORK_CLASS * tcpClient = new WEBSOCKETS_NETWORK_CLASS(_server->available());
#endif

        if(!tcpClient) {
            DEBUG_WEBSOCKETS("[WS-Client] creating Network class failed!");
            return;
        }

        ok = newClient(tcpClient);

        if(!ok) {
            // no free space to handle client
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
            IPAddress ip = tcpClient->remoteIP();
            DEBUG_WEBSOCKETS("[WS-Server] no free space new client from %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
#else
            DEBUG_WEBSOCKETS("[WS-Server] no free space new client\n");
#endif
            tcpClient->stop();
        }

#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
        delay(0);
    }
#endif

}
Esempio n. 18
0
int acquireLocks(char* serviceName, int servicePort, char* fileName,
                 int numLocks, int64_t offsets[], int64_t lengths[]) {
    int i;
    int lockID;

    printf("acquiring %d locks\n", numLocks);
    MessageClient client = newClient(serviceName, servicePort);

    Message m = newMessage();
    m->type = FILE_LOCK_CLIENT_SERVICE_CLIENT_MESSAGE;
    setStringParam(m, "functionName", "acquire");
    setStringParam(m, "fileName", fileName);
    setIntegerParam(m, "numLocks", numLocks);
    
    createLongArrayParam(m, "offsets", numLocks);
    createLongArrayParam(m, "lengths", numLocks);
    
    for (i = 0; i < numLocks; ++i) {
        setLongArrayParamValue(m, "offsets", i, offsets[i]);
        setLongArrayParamValue(m, "lengths", i, lengths[i]);
    }

    //printf("acquirelocks: Message to be sent:\n");
    //printMessage(m);

    Message reply = clientCall(client, m);
    clientDisconnect(client);
    //printf("acquirelocks: Reply:\n");
    //printMessage(reply);
    //printf("acquirelocks: before getIntegerParam()\n");
    lockID = getIntegerParam(reply, "lockID");

    destroyMessage(m);
    destroyMessage(reply);

    return lockID;
}
Esempio n. 19
0
/**
 * @brief Start listening
 *
 * If the preferred port is not available, a random port is chosen.
 *
 * @param preferredPort the default port to listen on
 */
bool BuiltinServer::start(quint16 preferredPort) {
	Q_ASSERT(_state == NOT_STARTED);
	_state = RUNNING;
	_server = new QTcpServer(this);

	connect(_server, SIGNAL(newConnection()), this, SLOT(newClient()));

	bool ok = _server->listen(QHostAddress::Any, preferredPort);

	if(!ok)
		ok = _server->listen(QHostAddress::Any, 0);

	if(ok==false) {
		_error = _server->errorString();
		logger::error() << "Error starting server:" << _error;
		delete _server;
		_server = 0;
		_state = NOT_STARTED;
		return false;
	}

	logger::info() << "Started listening on port" << port();
	return true;
}
Esempio n. 20
0
void Server::handleRequest(QHttpRequest *req, QHttpResponse *resp)
{
    new Responder(req, resp);
    emit newClient(req->remoteAddress());
}
Esempio n. 21
0
void MainServeur::ProcessData()
{
    QDataStream in(m_Client);

    if(taillePacket == 0)
    {
        if(m_Client->bytesAvailable() < (int)sizeof(quint16))
            return;

        in >> taillePacket;
    }
    if(m_Client->bytesAvailable() < taillePacket)
        return;

    quint8 header;
    in >> header;

    emit message(tr("Données reçues pour Header(%1) et pour taille(%2)").arg(QString::number(header), QString::number(taillePacket)));
    bool Authentified = m_Authentification->State() == AuthentificationSystem::Accepted;
    switch(header)
    {
        case CMSG_MESSAGE_LEGER:
        {
            QString messageRecu;
            in >> messageRecu;
            QString messageSecondRecu;
            in >> messageSecondRecu;

            QByteArray encryptedPassword;
            in >> encryptedPassword;

            emit message(tr("Message léger reçu depuis un client : %1\n%2\n%3").arg(messageRecu, messageSecondRecu, encryptedPassword.toHex()));
            break;
        }
        case CMSG_MESSAGE_CUSTOM:
        {
            /** Créer un comportement de test. **/
            break;
        }
        case CMSG_PING:
        {
            if(Authentified)
                emit message(tr("Ping reçu de %1.").arg(m_Authentification->GetUserName()));
            else
                emit message(tr("Ping reçu d'un client non authentifié."));

            Reponse(SMSG_PONG);
            break;
        }
        case CMSG_PONG:
        {
            if(Authentified)
                emit message(tr("Pong! Reçu de %1").arg(m_Authentification->GetUserName()));
            else
                emit message(tr("Pong! Reçu d'un client non authentifié."));
            break;
        }
        case CMSG_MESSAGE_AUTH:
        {
            QString userName;
            in >> userName;

            QByteArray password;
            in >> password;

            m_Authentification = AuthentificationSystem::Authentificate(userName, password);

            if(m_Authentification->Error() == AuthentificationSystem::NoError)
            {
                emit message(tr("Tentative d'authentification de %1 réussi !").arg(userName));
                emit newClient(m_Authentification->GetUserName(), m_Authentification->GetClasse());

                Reponse(SMSG_AUTHENTIFICATION_SUCCESS);
            }
            else if(m_Authentification->Error() == AuthentificationSystem::Double_Account_Detected)
            {
                emit message(tr("Tentative d'authentification de %1 raté car double compte détectée.").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
                // Kick("AuthentificationSystem: another account is already connected.");
            }
            else if(m_Authentification->Error() == AuthentificationSystem::Password_Incorrect)
            {
                emit message(tr("Tentative d'authentification de %1 raté car le mot de passe est incorrecte.").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
            }
            else if(m_Authentification->Error() == AuthentificationSystem::UserName_Not_Available)
            {
                emit message(tr("Tentative d'authentification de %1 raté car le nom de compte n'existe pas.").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
            }
            else
            {
                emit message(tr("Tentative d'authentification de %1 raté, raison inconnue !").arg(userName));
                Reponse(SMSG_AUTHENTIFICATION_FAILED);
            }

            break;
        }
        case CMSG_MESSAGE_HOMEWORKFOR:
        {
            if(!Authentified)
            {
                Reponse(SMSG_YOU_ARE_NOT_AUTHENTIFIED);
                emit message(tr("Demande de devoir de la part d'un client non authentifié !! (Refusé)"));
                break;
            }
            QString matiere = tr("all");
            bool needOnlyMatiere;
            in >> needOnlyMatiere;

            if(needOnlyMatiere)
                in >> matiere;

            emit message(tr("Demande de devoir reçu de la part de %1 en classe de %2").arg(m_Authentification->GetUserName(), m_Authentification->GetClasse()));

            QList<Devoir> devoirs = SQLServerSupervisor::GetInstance()->LoadHomeworks(m_Authentification, matiere);
            SendHomeworks(devoirs);
            break;
        }
        case CMSG_MESSAGE_LISTMATIERE:
        {
            if(Authentified)
            {
                QStringList listMatiere = SQLServerSupervisor::GetInstance()->GetAllMatiereFromClasse(m_Authentification);
                emit message(tr("Demande des matières disponibles pour la classe %1 de %2").arg(m_Authentification->GetClasse(), m_Authentification->GetUserName()));
                SendMatieres(listMatiere);
            }
            else
            {
                emit message(tr("Demande des matières disponibles d'un utilisateur inconnu."));
            }

            break;
        }
        default:
        {
            emit message(tr("Header inconnu détecté : 0x%1").arg(QString::number(header, 16).toUpper()));
            break;
        }
    }

    taillePacket = 0;
}
Esempio n. 22
0
void ClientWidget::loadUi()
{
	splitter->setStretchFactor(0, 1);
	setIcon( QString(":/TransactionRecord/Resources/clients.png") );
	setName( "ClientWidget" );

	//------------------------------------------

	QStringList cList;
	cList << tr("id") << tr("Name") << tr("Phone") << tr("Phone 2") << tr("Fax") << tr("Mail") << tr("ICQ") << tr("Other");
	clientTable->createColumns( cList );

	QStringList aList;
	aList << tr("id") << tr("Number") << tr("Currency") << tr("Saldo");
	accountTable->createColumns( aList );
	accountTable->setColumnForDouble(3);

	createSortConnection( clientTable );

	//------------------------------------------
	newClientAction = new QAction( this );
	newClientAction->setText( tr("New client") );
	newClientAction->setIcon( QIcon(":/TransactionRecord/Resources/client_add.png") );
	newClientAction->setShortcut( tr("Ctrl+N") );
	
	editClientAction = new QAction( this );
	editClientAction->setText( tr("Edit client") );
	editClientAction->setIcon( QIcon(":/TransactionRecord/Resources/edit.png") );
	editClientAction->setShortcut( tr("Ctrl+E") );

	removeClientAction = new QAction( this );
	removeClientAction->setText( tr("Delete client") );
	removeClientAction->setShortcut( tr("Del") );

	newClientAccountAction = new QAction( this );
	newClientAccountAction->setText( tr("New client account") );
	newClientAccountAction->setShortcut( tr("Ctrl+Shift+N") );

	removeClientAccountAction = new QAction( this );
	removeClientAccountAction->setText( tr("Delete client account") );
	removeClientAccountAction->setShortcut( tr("Ctrl+Del") );

	reloadAction = new QAction( this );
	reloadAction->setText( tr("Reload") );
	reloadAction->setIcon( QIcon(":/TransactionRecord/Resources/reload.png") );
	reloadAction->setShortcut( tr("Ctrl+R") );

	toolBar->addAction( newClientAction, 1 );
	toolBar->addAction( editClientAction, 1 );
	toolBar->addAction( removeClientAction, 0, 1 );
	toolBar->addAction( newClientAccountAction, 1 );
	toolBar->addAction( removeClientAccountAction, 0, 1 );
	toolBar->addAction( reloadAction, 1 );

	connect( newClientAction, SIGNAL( triggered() ), this, SLOT( newClient() ) );
	connect( editClientAction, SIGNAL( triggered() ), this, SLOT( editClient() ) );
	connect( newClientAccountAction, SIGNAL( triggered() ), this, SLOT( newClientAccount() ) );
	connect( removeClientAccountAction, SIGNAL( triggered() ), this, SLOT( removeClientAccount() ) );
	connect( removeClientAction, SIGNAL( triggered() ), this, SLOT( removeClientRequest() ) );
	connect( reloadAction, SIGNAL( triggered() ), this, SLOT( reload() ) );

	connect( allRadioButton, SIGNAL( clicked() ), this, SLOT( reload() ) );
	connect( clientsRadioButton, SIGNAL( clicked() ), this, SLOT( reload() ) );

	connect( clientTable, SIGNAL( rowSelected(int) ), this, SLOT( enableActions() ) );
	connect( clientTable, SIGNAL( rowSelected(int) ), this, SLOT( accountRequest(int) ) );
	connect( clientTable, SIGNAL( cellDoubleClicked(int, int) ), this, SLOT( editClient() ) );

	connect( accountTable, SIGNAL( cellDoubleClicked( int, int ) ), this, SLOT( doubleClicked( int, int ) ) );
	connect( accountTable, SIGNAL( rowSelected(int) ), this, SLOT( enableActions() ) );

	connect( qApp, SIGNAL( focusChanged(QWidget *, QWidget *) ), this, SLOT( changeFocus(QWidget *, QWidget *) ) );
}
Esempio n. 23
0
void ItalcVncConnection::doConnection()
{
	QMutex sleeperMutex;

	while( !m_stopped && m_state != Connected ) // try to connect as long as the server allows
	{
		m_cl = rfbGetClient( 8, 3, 4 );
		m_cl->MallocFrameBuffer = hookNewClient;
		m_cl->canHandleNewFBSize = true;
		m_cl->GotFrameBufferUpdate = hookUpdateFB;
		m_cl->FinishedFrameBufferUpdate = hookFinishFrameBufferUpdate;
		m_cl->HandleCursorPos = hookHandleCursorPos;
		m_cl->GotCursorShape = hookCursorShape;
		m_cl->GotXCutText = hookCutText;
		rfbClientSetClientData( m_cl, 0, this );

		m_mutex.lock();

		if( m_port < 0 ) // port is invalid or empty...
		{
			m_port = PortOffsetVncServer;
		}

		if( m_port >= 0 && m_port < 100 )
		{
			 // the user most likely used the short form (e.g. :1)
			m_port += PortOffsetVncServer;
		}

		free( m_cl->serverHost );
		m_cl->serverHost = strdup( m_host.toUtf8().constData() );
		m_cl->serverPort = m_port;

		m_mutex.unlock();

		emit newClient( m_cl );

		int argc;
		if( rfbInitClient( m_cl, &argc, NULL ) )
		{
			emit connected();

			m_state = Connected;
			if( m_framebufferUpdateInterval < 0 )
			{
				rfbClientSetClientData( m_cl, (void *) 0x555, (void *) 1 );
			}
		}
		else
		{
			// guess reason why connection failed based on the state,
			// libvncclient left the rfbClient structure
			if( argc < 0 )
			{
				m_state = HostUnreachable;
			}
			else if( argc > 0 )
			{
				m_state = AuthenticationFailed;
			}
			else
			{
				// failed for an unknown reason
				m_state = ConnectionFailed;
			}

			// do not sleep when already requested to stop
			if( m_stopped )
			{
				break;
			}

			// wait a bit until next connect
			sleeperMutex.lock();
			if( m_framebufferUpdateInterval > 0 )
			{
				m_updateIntervalSleeper.wait( &sleeperMutex,
												m_framebufferUpdateInterval );
			}
			else
			{
				// default: retry every second
				m_updateIntervalSleeper.wait( &sleeperMutex, 1000 );
			}
			sleeperMutex.unlock();
		}
	}

	QTime lastFullUpdate = QTime::currentTime();

	// Main VNC event loop
	while( !m_stopped )
	{
		int timeout = 500;
		if( m_framebufferUpdateInterval < 0 )
		{
			timeout = 100*1000;	// 100 ms
		}
		const int i = WaitForMessage( m_cl, timeout );
		if( i < 0 )
		{
			break;
		}
		else if( i )
		{
			// read and process remaining messages many messages as available
			bool handledOkay = true;
			while( WaitForMessage( m_cl, 0 ) && handledOkay )
			{
				handledOkay = HandleRFBServerMessage( m_cl );
			}
			if( handledOkay == false )
			{
				break;
			}
		}
		else
		{
		/*	// work around a bug in UltraVNC on Win7 where it does not handle
			// incremental updates correctly
			int msecs = lastFullUpdate.msecsTo( QTime::currentTime() );
			if( ( m_framebufferUpdateInterval > 0 &&
					msecs > 10*m_framebufferUpdateInterval ) ||
				( m_framebufferUpdateInterval == 0 && msecs > 1000 ) )
			{
				SendFramebufferUpdateRequest( m_cl, 0, 0,
						framebufferSize().width(), framebufferSize().height(),
						false );
				lastFullUpdate = QTime::currentTime();
			}*/
		}

		m_mutex.lock();

		while( !m_eventQueue.isEmpty() )
		{
			ClientEvent * clientEvent = m_eventQueue.dequeue();

			// unlock the queue mutex during the runtime of ClientEvent::fire()
			m_mutex.unlock();

			clientEvent->fire( m_cl );
			delete clientEvent;

			// and lock it again
			m_mutex.lock();
		}

		m_mutex.unlock();

		if( m_framebufferUpdateInterval > 0 && m_stopped == false )
		{
			sleeperMutex.lock();
			m_updateIntervalSleeper.wait( &sleeperMutex,
												m_framebufferUpdateInterval );
			sleeperMutex.unlock();
		}
	}

	if( m_state == Connected && m_cl )
	{
		rfbClientCleanup( m_cl );
	}

	m_state = Disconnected;
}
Esempio n. 24
0
void HttpServerWorker::serveClient(QTcpSocket *client)
{
    emit newClient(client);
}
Esempio n. 25
0
void InTcpServer::incomingConnection(int socketDescriptor)
#endif
{
    emit newClient(socketDescriptor);
}
Esempio n. 26
0
void KFMServer::slotAccept( KSocket * _sock )
{
    KfmServIpc * i = new KFMClient( _sock, this );
    emit newClient( i );
}
void QDeclarativeBluetoothService::new_connection()
{
    emit newClient();
}
Esempio n. 28
0
/* service traffic from clients and drivers */
void
indiRun(void)
{
	fd_set rs, ws;
        int maxfd=0;
	int i, s;

	/* init with no writers or readers */
	FD_ZERO(&ws);
	FD_ZERO(&rs);

        if (fifo.name && fifo.fd >=0)
        {
           FD_SET(fifo.fd, &rs);
           maxfd = fifo.fd;
        }

	/* always listen for new clients */
	FD_SET(lsocket, &rs);
        if (lsocket > maxfd)
                maxfd = lsocket;

	/* add all client readers and client writers with work to send */
	for (i = 0; i < nclinfo; i++) {
	    ClInfo *cp = &clinfo[i];
	    if (cp->active) {
		FD_SET(cp->s, &rs);
		if (nFQ(cp->msgq) > 0)
		    FD_SET(cp->s, &ws);
		if (cp->s > maxfd)
		    maxfd = cp->s;
	    }
	}

	/* add all driver readers and driver writers with work to send */
        for (i = 0; i < ndvrinfo; i++)
        {
	    DvrInfo *dp = &dvrinfo[i];
            if (dp->active)
            {
                FD_SET(dp->rfd, &rs);
                if (dp->rfd > maxfd)
                   maxfd = dp->rfd;
                if (dp->pid != REMOTEDVR)
                {
                   FD_SET(dp->efd, &rs);
                   if (dp->efd > maxfd)
                      maxfd = dp->efd;
                }
                if (nFQ(dp->msgq) > 0)
                {
                   FD_SET(dp->wfd, &ws);
                   if (dp->wfd > maxfd)
                       maxfd = dp->wfd;
                }
            }
	}

	/* wait for action */
	s = select (maxfd+1, &rs, &ws, NULL, NULL);
	if (s < 0) {
	    fprintf (stderr, "%s: select(%d): %s\n", indi_tstamp(NULL), maxfd+1,
							    strerror(errno));
	    Bye();
	}


        /* new command from FIFO? */
        if (s > 0 && fifo.fd >= 0 && FD_ISSET(fifo.fd, &rs))
        {
            newFIFO();
            s--;
        }

	/* new client? */
	if (s > 0 && FD_ISSET(lsocket, &rs)) {
	    newClient();
	    s--;
	}

	/* message to/from client? */
	for (i = 0; s > 0 && i < nclinfo; i++) {
	    ClInfo *cp = &clinfo[i];
	    if (cp->active) {
		if (FD_ISSET(cp->s, &rs)) {
		    if (readFromClient(cp) < 0)
			return;	/* fds effected */
		    s--;
		}
		if (s > 0 && FD_ISSET(cp->s, &ws)) {
		    if (sendClientMsg(cp) < 0)
			return;	/* fds effected */
		    s--;
		}
	    }
	}

	/* message to/from driver? */
	for (i = 0; s > 0 && i < ndvrinfo; i++) {
	    DvrInfo *dp = &dvrinfo[i];
	    if (dp->pid != REMOTEDVR && FD_ISSET(dp->efd, &rs)) {
		if (stderrFromDriver(dp) < 0)
		    return;	/* fds effected */
		s--;
	    }
	    if (s > 0 && FD_ISSET(dp->rfd, &rs)) {
        if (readFromDriver(dp) < 0)
            return;	/* fds effected */
		s--;
	    }
	    if (s > 0 && FD_ISSET(dp->wfd, &ws) && nFQ(dp->msgq) > 0) {
        if (sendDriverMsg(dp) < 0)
           return;	/* fds effected */
		s--;
	    }
	}
}
Esempio n. 29
0
SensingServer::SensingServer(QObject *parent) :
	QTcpServer(parent)
{
	connect(this, SIGNAL(newConnection()), this, SLOT(newClient()));
}