Ejemplo n.º 1
0
void CServerApp::resetServer(const CEvent&, void*)
{
	LOG((CLOG_DEBUG1 "resetting server"));
	stopServer();
	cleanupServer();
	startServer();
}
Ejemplo n.º 2
0
void MainDaemon::answerRequest(){
  //curSock->waitForReadyRead(1000); //wait max 1 second for the request from the client
  static bool working = false;
  if(working || curSock==0){ return; }
  working = true;
  QStringList req, out;
  bool stopdaemon=false;
  QTextStream stream(curSock);
  bool done = false;
  while(!stream.atEnd()){
    req = QString(stream.readLine()).split(" ");
    //qDebug() << " - Request:" << req;
    //qDebug() << "Request Received:" << req;
    if(req.join("")=="shutdowndaemon"){ stopdaemon=true; done=true; break; }
    if(req.join("")=="[FINISHED]"){ done = true; break; }
    else{ 
	
      QString res = SYSTEM->runRequest(req);
      //For info not available, try once more time as it can error unexpectedly if it was 
	// stuck waiting for a sync to finish
      //if(res =="[ERROR] Information not available"){ res = DATA->fetchInfo(req); }
      out << "[INFOSTART]"+ res;
    }
  }
  //Now write the output to the socket and disconnect it
  //qDebug() << " - Request replied:" << done;
  stream << out.join("\n");
  //curSock->disconnectFromServer();
  working = false;
  if(done){ stream << "\n[FINISHED]"; }
  else{ QTimer::singleShot(0,this, SLOT(answerRequest()) ); }
  if(stopdaemon){ QTimer::singleShot(10, this, SLOT(stopServer())); }
}
Ejemplo n.º 3
0
void MainWindow::on_actionConfigure_triggered()
{
    if(serverState == ServerWorking) {
        int w = QMessageBox::warning(this, tr("Reconfigure Database?"),
                                     tr("Server is working now...\n"
                                        "you must stop server, if you want to reconfigure server.\n"
                                        "Are you sure to stop server?"),
                                     tr("Yes, I sure"), tr("No, thanks"));
        if(w == 0)
            stopServer();
        else
            return;
    }
    DatabaseConfigureDialog dbConfDialog;
    dbConfDialog.setSqlDatabase(&db);
    // init configure
    if(db) {
        dbConfDialog.setHostName(db->hostName());
        dbConfDialog.setHostPort(db->port());
        dbConfDialog.setUserName(db->userName());
        dbConfDialog.setPassword(db->password());
        dbConfDialog.setDatabaseName(db->databaseName());
    }
    dbConfDialog.exec();
}
Ejemplo n.º 4
0
void MainWindow::on_actionStartOrStop_triggered()
{
    if(serverState == ServerStop)
        startServer();
    else
        stopServer();
}
Ejemplo n.º 5
0
void MainWindow::startServer()
{
    if(!db || !db->isOpen()) {
        QMessageBox::information(this, tr("No database"),
                                 tr("you need to configure database for server at first..."));
        return;
    }
    if(server) {
        server->close();
        delete server;
    }

    server = new FSEServer(this);
    server->setDatabase(db);

    connect(server, SIGNAL(acceptError(QAbstractSocket::SocketError)),
            this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(server, SIGNAL(errorString(QString)),
            this, SLOT(logCollect(QString)));
    connect(server, SIGNAL(debugString(QString)),
            this, SLOT(logCollect(QString)));

    if(server->listen(QHostAddress(IPv4), serverPort)) {
        logCollect(tr("start to listen ") + IPv4 + ":" +QString::number(serverPort));
        stateChange(ServerWorking);
    }
    else {
        qDebug() << "start failed" << server->serverError();
        stopServer();
    }
}
Ejemplo n.º 6
0
/*!
  Handles the changed \a state of the connection manager.
*/
void TicTacServer::handleConnectionManagerStateChanged(int state)
{
    qDebug() << "TicTacServer::handleConnectionManagerStateChanged():" << state;

    switch (state) {
    case ConnectionManager::NotConnected: {
        stopServer();
        break;
    }
    case ConnectionManager::Connecting: {
        break;
    }
    case ConnectionManager::Connected: {
        // Start server, in case of pending start call
        if (mState == Stopped || mState == Starting) {
            startServer();
        }

        break;
    }
    case ConnectionManager::Disconnecting: {
        break;
    }
    case ConnectionManager::Failed: {
        mBroadcastTimer.stop();
        setState(ConnectionError);
        break;
    }
    }
}
Ejemplo n.º 7
0
int main( int argc, char ** argv )
{
    QCoreApplication a(argc, argv);
    //Check whether running as root
    if( getuid() != 0){
      qDebug() << "pc-restserver must be started as root!";
      return 1;
    }
      //Setup the log file
    if(DEBUG){
      qDebug() << "pc-restserver Log File:" << logfile.fileName();
      if(QFile::exists(logfile.fileName()+".old")){ QFile::remove(logfile.fileName()+".old"); }
      if(logfile.exists()){ QFile::rename(logfile.fileName(), logfile.fileName()+".old"); }
      //Make sure the parent directory exists
      if(!QFile::exists("/var/log")){
        QDir dir;
        dir.mkpath("/var/log");
      }
      logfile.open(QIODevice::WriteOnly | QIODevice::Append);
      qInstallMessageHandler(MessageOutput);
    }
      
    //Create and start the daemon
    qDebug() << "Starting the PC-BSD REST server interface....";
    WebServer *w = new WebServer(); 
    if( w->startServer() ){
      //Now start the event loop
      QTimer::singleShot(1000, w, SLOT(stopServer()) ); //for testing purposes
      int ret = a.exec();
      logfile.close();
      return ret;
    }else{
      return 1;
    }
}
Ejemplo n.º 8
0
int main(int argc, char * argv[]){
	
	int cclients = 10;
	int sentMsg = 0;
	printf("Server iniciado para %d clientes.\n", cclients);

	message_t incomingMsg;
	message_t msgsent;
	char * word = "Mensaje del Server";
	
	ipc_t server = (ipc_t) fifoServe(cclients);
	server->stop = 0;

	while(sentMsg != 1000){
		if((incomingMsg = qget(server->inbox)) != NULL){
			printf("%d. Server recibio: %s\n", sentMsg, incomingMsg->data);
			
			printf("Manda mensaje a:%d.\n", incomingMsg->header.from);
			qput(server->outbox, (msgsent = mnew(0,incomingMsg->header.from, strlen(word) + 1, word)));
			mdel(msgsent);

			mdel(incomingMsg);
			sentMsg++;
		}
	}
	stopServer(server);
}
Ejemplo n.º 9
0
//------------------------------------------------------------------------------
My4Server::My4Server(QObject *parent)
    : QTcpServer(parent)
{
    if (listen(QHostAddress::Any, 7700))
        qDebug("qt4server");
    QTimer::singleShot(5000, this, SLOT(stopServer()));
}
Ejemplo n.º 10
0
bool TestDebugger::RunTests(const std::string &which) {
  bool ret = true;

  unlink("/tmp/hphpd_test_error.log");
  AsyncFunc<TestDebugger> func(this, &TestDebugger::runServer);
  func.start();

  {
    // To make sure TestSanity always get run
    std::string which = "TestSanity";
    RUN_TEST(TestSanity);
  }
  RUN_TEST(TestBasic);
  RUN_TEST(TestBreak);
  RUN_TEST(TestFlow);
  RUN_TEST(TestStack);
  RUN_TEST(TestEval);
  RUN_TEST(TestException);
  RUN_TEST(TestInfo);
  RUN_TEST(TestWebRequest);

  stopServer();
  func.waitForEnd();

  return ret;
}
Ejemplo n.º 11
0
void main(void)
{
        int tmpFlag;
        tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
        tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
        tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
        _CrtSetDbgFlag( tmpFlag );

        readConfigFile("C:\\Simulink_SimServer\\io_config.cfg");

        PortNumber = 80;

        startServer();

        printf("\n");
        printf("***** Press any key to quit *****\n");
        printf("\n");

        while(1)
        {

                if(kbhit())
                {
                        break;
                }
        }

        stopServer();

#ifdef TEST_HARNESS
_ASSERTE(_CrtCheckMemory());
#endif
}
Ejemplo n.º 12
0
/**
 * Play back specified file.
 *
 * @param file
 *        file path.
 * @return
 *        0 if file playback started, 1 if output was locked, other values on errors.
 */
int
SrvPlayFile( const char * file )
{
	int status;
	
	stopServer();
	
	LOCK_PLAYMUTEX();
	strcpy(trackName, file);
	playtype = NPT_FILE;
	going = 1;
	everPlayed = 0;
	UNLOCK_PLAYMUTEX();

	status = playFile(file);
	if (status) stopPlaying();
	else
	{
		LOCK_PLAYMUTEX();
		playState = NMS_STATUS_PLAYER_PLAY; 
		errorStatus = NMS_STATUS_OK;
		UNLOCK_PLAYMUTEX();
	}
	return status;
}
Ejemplo n.º 13
0
/**
 * Stop current playback.
 */
void
SrvStop( void )
{
	int loc_going;
	int loc_fileIdx;
	int loc_everPlayed;
	int loc_playtype;

	LOCK_PLAYMUTEX();
	loc_going = going;
	loc_fileIdx = fileIdx;
	loc_playtype = playtype;
	UNLOCK_PLAYMUTEX();

	if (loc_going)
	  // if playing, set history before shutdown.
	{

		char * path = NULL;
		char buf[PATH_MAX];
		DBGMSG("Stop server playback.");
		switch (loc_playtype)
		{
		case NPT_FILE:
			LOCK_PLAYMUTEX();
			path = strcpy(buf, trackName); 
			UNLOCK_PLAYMUTEX();
			break;
		case NPT_DIR:
			path = nextFileFromDir(loc_fileIdx,buf,PATH_MAX); break;
		default: //history not supported.
			WPRINT("play history not supported.");
			break;
		}

		LOCK_PLAYMUTEX();
		loc_fileIdx = fileIdx;
		loc_everPlayed = everPlayed;
		UNLOCK_PLAYMUTEX();

		if (path)
		{
			int mark;

			LOCK_PLAYMUTEX();			
			mark = playtime;
			UNLOCK_PLAYMUTEX();

			if (loc_everPlayed) SetPlayHistory(loc_playtype, loc_fileIdx, mark, path);
		}
	}	

	stopServer();

	LOCK_PLAYMUTEX();
	// player has been stop upon user request.
	errorStatus = NMS_STATUS_PLAYER_STOPPED;
	UNLOCK_PLAYMUTEX();
}
Ejemplo n.º 14
0
void delServer(Server * srv)
{
    //make sure to stop the server thread
    stopServer(srv);
    close(srv->socket);
    free(srv);
    return;
}
Ejemplo n.º 15
0
//------------------------------------------------------------------------------
My3Server::My3Server(QObject *parent)
    : Q3ServerSocket(7700, 1, parent), m_socket(0)
{
    if (ok())
        qDebug("qt3server");

    QTimer::singleShot(5000, this, SLOT(stopServer()));
}
Ejemplo n.º 16
0
DatabaseMysql::~DatabaseMysql()
{
	stopServer();

	//Free Mysql library pointers for last ~DB
	if (--db_count == 0)
		mysql_library_end();
}
Ejemplo n.º 17
0
void CServerDoc::delSelectedServer(void)
{
	ServerControl* sc = getSelectedServer();
	stopServer(sc);
	m_Servers.RemoveAt(m_SelectedServer);
	delete sc;
	m_SelectedServer -= 1;
	writeFile(false);
}
Ejemplo n.º 18
0
Server::~Server() {
    stopServer();
	if (incomingListener) {
		incomingListener->killListener();
	}
	if (outgoingListener) {
		outgoingListener->killListener();
	}
}
Ejemplo n.º 19
0
void 
CServerApp::handleSuspend(const CEvent&, void*)
{
	if (!m_suspended) {
		LOG((CLOG_INFO "suspend"));
		stopServer();
		m_suspended = true;
	}
}
Ejemplo n.º 20
0
TennisServer::~TennisServer()
{
    if(stream){
        QByteArray b;
        QDataStream s(&b, QIODevice::WriteOnly);
        s << QString("D");
        clientSocket->write(b);
    }

    stopServer();
}
Ejemplo n.º 21
0
bool evaluate(char* command) {
  if (strcmp(HELP, command) == 0) {
    printHelp();
  } else if (strcmp(STOP, command) == 0) {
    stopServer();
    return false;
  } else {
    WRN("Undefined command: %s", command);
  }
  return true;
}
Ejemplo n.º 22
0
bool ConcreteDatabase::initialise(Poco::Logger& dbLogger, const KeyValueColl& connParams, bool logSql, const string& logDir, size_t nConns)
{
	stopServer();

	_logger = &dbLogger;

	//Enable logging of SQL commands (usually only high-risk commands)
	//(See method: PExecuteLog)
	_shouldLogSQL = logSql;
	_sqlLogsDir = logDir;
	if(!_sqlLogsDir.empty())
	{
		if((_sqlLogsDir.at(_sqlLogsDir.length()-1)!='/') && (_sqlLogsDir.at(_sqlLogsDir.length()-1)!='\\'))
			_sqlLogsDir.append("/");
	}

	//create DB connections

	//setup connection pool size
	size_t poolSize = nConns;
	if(poolSize < MIN_CONNECTION_POOL_SIZE)
		poolSize = MIN_CONNECTION_POOL_SIZE;
	else if(poolSize > MAX_CONNECTION_POOL_SIZE)
		poolSize = MAX_CONNECTION_POOL_SIZE;

	//initialize and connect all the connections
	_queryConns.clear();
	_queryConns.reserve(poolSize);
	try
	{
		//create and initialize the sync connection pool
		for (size_t i=0; i<poolSize; i++)
		{
			unique_ptr<SqlConnection> pConn = createConnection(connParams);
			pConn->connect();

			_queryConns.push_back(pConn.release());
		}

		//create and initialize connection for async requests
		_asyncConn = createConnection(connParams);
		_asyncConn->connect();
	}
	catch(const SqlConnection::SqlException& e)
	{
		e.toLog(dbLogger);
		return false;
	}

	_resultQueue.clear();

	initDelayThread();
	return true;
}
void CopySenderServer::requestHandler(QString data){

    JSON *instance = &JSON::instance();

    //go and parse the json to an object concurrently...
    QFuture <QVariantMap>future = QtConcurrent::run(instance, &JSON::parse, data);

    const QVariantMap jsonObject = future.result();//finally retrieve the jsonObject after it has been parsed
    QVariant handler = jsonObject.value("handler");

    if(!handler.toString().compare("QVariant(, )")){
        qDebug()<< "invalid JSON String::"<<data;
    }

    if(firstTalk){
        if(!handler.toString().compare("HelloCopySender")){
            //check whether the machine is the right machine that should connect to it...
            if(jsonObject.value("machineID").toString().compare(QString::number(machineId))){
               socket->disconnectFromHost();
               return;
            }else{
                //if it is the right machine continue
                firstTalk = false;
                //stop the server since you don't want to allow any other connections
                stopServer();
            }
        }else{
            socket->disconnectFromHost();
            return;
        }


        QString jsonMessage = startJSONMessage();
        appendJSONValue(jsonMessage, "handler", "HelloCopyReceiver", false);
        endJSONMessage(jsonMessage);


        sendJSONMessage(socket, jsonMessage);
        return;
    }

    if(!handler.toString().compare("SendDifferences"))
        SendDifferences();
    else

    if(!handler.toString().compare("BuildFileSumMD5"))
        BuildFileSumMD5(jsonObject);
    else

    if(!handler.toString().compare("NotifyCopySuccess"))
        NotifyCopySuccess(jsonObject);

}
Ejemplo n.º 24
0
void main(void)
{
	/* Configure the oscillator for the device */
	ConfigureOscillator();



	/* Initialize I/O and Peripherals for application */
	 InitApp();

	W5200_nRESET = 0;
	__delay_us(5);
	W5200_nRESET = 1;
	__delay_ms(50);
	__delay_ms(50);
	__delay_ms(50);
	__delay_ms(50);
	
	/* Initialize application settings */
	InitSettings();
	
	/* Initialize TCP server */
	initServer(&macAddress, &gateway, &netmask);
	startServer(&localEndpoint);

        LED = 1;

    while(1)
    {
		if(clientConnected())
		{
			if(dataAvailable())
			{
				uint16_t length = getReceivedLength();
				if(length > MAX_BUFFER)
				{
					// Limit maximum buffer size to avoid ram saturation due to packet flooding, a normal communication is shorter anyway
					length = MAX_BUFFER;
				}
				
				uint8_t buffer[MAX_BUFFER];
				getReceivedData(buffer, length);
				
				parseCommand(buffer[0], buffer, length);
				
				stopServer();
				startServer(&localEndpoint);
			}
			checkClientDisconnection();
		}		
    }

}
Ejemplo n.º 25
0
void CServerDoc::stopAllServers(bool dontStop)
{
	for (int i = 0; i <= m_Servers.GetUpperBound(); i++)
	{
		ServerControl* sc = m_Servers[i];
		if (sc)
		{
			sc->dontStopServer(dontStop);
			stopServer(sc);
		}
	}
}
Ejemplo n.º 26
0
void NetworkManager::startServer() {
	if (state == NetworkStateServer) stopServer();
	if (state == NetworkStateClient) stopClient();

	LOG("Starting server...");
	
	state = NetworkStateServer;

	server = new GameServer(GAME_PORT);
	if (server->start() < 0) {
		LOG("ERROR: SERVER FAILED TO START.");
		return;
	}
}
Ejemplo n.º 27
0
void NetworkManager::startClient(const char* host) {
	if (state == NetworkStateServer) stopServer();
	if (state == NetworkStateClient) stopClient();

	LOG("Starting client...");

	state = NetworkStateClient;

	client = new GameClient(host, GAME_PORT);
	if (client->connect() < 0) {
		LOG("ERROR: CLIENT FAILED TO CONNECT.");
		return;
	}
}
Ejemplo n.º 28
0
void MainWidget::createTrayIcon()
{    
    trayIcon = createTrayObject(this);
    trayIcon->init();

#ifndef Q_OS_WIN32
    trayIcon->setIcon("qcma_off");
#else
    trayIcon->setIcon("tray/qcma_off_16");
#endif
    trayIcon->show();

    connect(trayIcon, SIGNAL(openConfig()), this, SLOT(openConfig()));
    connect(trayIcon, SIGNAL(openManager()), this, SLOT(openManager()));
    connect(trayIcon, SIGNAL(refreshDatabase()), this, SLOT(refreshDatabase()));
    connect(trayIcon, SIGNAL(showAboutDialog()), this, SLOT(showAboutDialog()));
    connect(trayIcon, SIGNAL(showAboutQt()), this, SLOT(showAboutQt()));
    connect(trayIcon, SIGNAL(stopServer()), this, SLOT(stopServer()));

    connect(managerForm, SIGNAL(deviceConnected(QString)), this, SLOT(deviceConnect(QString)));
    connect(managerForm, SIGNAL(deviceDisconnected()), this, SLOT(deviceDisconnect()));
    connect(managerForm, SIGNAL(messageSent(QString)), this, SLOT(receiveMessage(QString)));
}
Ejemplo n.º 29
0
void Server::stopServer() { //untested code but 98% sure it'll do.
	CLIENT_DATA * clientData;
	isServerStopped = true;

	if(serverSocks.size() > 0) {

		for(unsigned int x = 0; x < serverSocks.size(); x++) {
				clientData = serverSocks[x];
				deleteClient(clientData->index);
		}

		stopServer(); //recursive: we need to keep calling this until size() is zero.

	}

}
Ejemplo n.º 30
0
/**
 * @brief SingleApplication::~SingleApplication
 *  Destructor
 */
SingleApplication::~SingleApplication()
{
  if(_shouldContinue)
  {
      emit stopServer();
      if(!server->wait(5000))
      {
          qDebug() << "TERMINATOR RETURNS BACK single application! 8-)";
          server->terminate();
          qDebug() << "Wait for nothing";
          server->wait();
          qDebug() << "Terminated!";
      }
  }
  delete server;
}