MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), server(NULL) { ui->setupUi(this); setWindowTitle(tr("Sanguosha") + " " + Sanguosha->getVersionNumber()); scene = NULL; connection_dialog = new ConnectionDialog(this); connect(ui->actionStart_Game, SIGNAL(triggered()), connection_dialog, SLOT(exec())); connect(connection_dialog, SIGNAL(accepted()), this, SLOT(startConnection())); config_dialog = new ConfigDialog(this); connect(ui->actionConfigure, SIGNAL(triggered()), config_dialog, SLOT(show())); connect(config_dialog, SIGNAL(bg_changed()), this, SLOT(changeBackground())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(ui->actionAcknowledgement_2, SIGNAL(triggered()), this, SLOT(on_actionAcknowledgement_triggered())); StartScene *start_scene = new StartScene; QList<QAction *> actions; actions << ui->actionStart_Game << ui->actionStart_Server << ui->actionReplay << ui->actionConfigure << ui->actionGeneral_Overview << ui->actionCard_Overview << ui->actionScenario_Overview << ui->actionAbout; foreach(QAction *action, actions) start_scene->addButton(action); view = new FitView(scene); setCentralWidget(view); restoreFromConfig(); BackLoader::preload(); gotoScene(start_scene); addAction(ui->actionShow_Hide_Menu); addAction(ui->actionFullscreen); connect(ui->actionRestart_Game, SIGNAL(triggered()), this, SLOT(startConnection())); connect(ui->actionReturn_to_Main_Menu, SIGNAL(triggered()), this, SLOT(gotoStartScene())); systray = NULL; }
void PropertyPanel::connectButtonClicked() { if(!port) return; // sanity check pvConnectionButton->setChecked( true ); emit startConnection( port ); }
void MainWindow::on_actionStart_Server_triggered() { ServerDialog *dialog = new ServerDialog(this); int accept_type = dialog->config(); if (accept_type == 0) return; server = new Server(this); if (!server->listen()) { QMessageBox::warning(this, tr("Warning"), tr("Can not start server!")); return; } server->checkUpnpAndListServer(); if (accept_type == 1) { server->daemonize(); ui->actionStart_Game->disconnect(); connect(ui->actionStart_Game, SIGNAL(triggered()), this, SLOT(startGameInAnotherInstance())); StartScene *start_scene = qobject_cast<StartScene *>(scene); if (start_scene) { start_scene->switchToServer(server); if (Config.value("EnableMinimizeDialog", false).toBool()) this->on_actionMinimize_to_system_tray_triggered(); } } else { Config.HostAddress = "127.0.0.1"; startConnection(); } }
void MainWindow::restartConnection(){ ClientInstance = NULL; delete Self; Self = NULL; startConnection(); }
void MainWindow::enterRoom(){ // add current ip to history if(!Config.HistoryIPs.contains(Config.HostAddress)){ Config.HistoryIPs << Config.HostAddress; Config.HistoryIPs.sort(); Config.setValue("HistoryIPs", Config.HistoryIPs); } ui->actionStart_Game->setEnabled(false); ui->actionStart_Server->setEnabled(false); ui->actionAI_Melee->setEnabled(false); RoomScene *room_scene = new RoomScene(this); ui->actionView_Discarded->setEnabled(true); ui->actionView_distance->setEnabled(true); ui->actionServerInformation->setEnabled(true); ui->actionKick->setEnabled(true); ui->actionSurrender->setEnabled(true); ui->actionSaveRecord->setEnabled(true); connect(ui->actionView_Discarded, SIGNAL(triggered()), room_scene, SLOT(toggleDiscards())); connect(ui->actionView_distance, SIGNAL(triggered()), room_scene, SLOT(viewDistance())); connect(ui->actionServerInformation, SIGNAL(triggered()), room_scene, SLOT(showServerInformation())); connect(ui->actionKick, SIGNAL(triggered()), room_scene, SLOT(kick())); connect(ui->actionSurrender, SIGNAL(triggered()), room_scene, SLOT(surrender())); connect(ui->actionSaveRecord, SIGNAL(triggered()), room_scene, SLOT(saveReplayRecord())); connect(ui->actionExpand_dashboard, SIGNAL(toggled(bool)), room_scene, SLOT(adjustDashboard(bool))); if(Config.value("UI/ExpandDashboard").toBool()) ui->actionExpand_dashboard->toggle(); if(ServerInfo.FreeChoose){ ui->menuCheat->setEnabled(true); connect(ui->actionGet_card, SIGNAL(triggered()), ui->actionCard_Overview, SLOT(trigger())); connect(ui->actionDeath_note, SIGNAL(triggered()), room_scene, SLOT(makeKilling())); connect(ui->actionDamage_maker, SIGNAL(triggered()), room_scene, SLOT(makeDamage())); connect(ui->actionRevive_wand, SIGNAL(triggered()), room_scene, SLOT(makeReviving())); connect(ui->actionSend_lowlevel_command, SIGNAL(triggered()), this, SLOT(sendLowLevelCommand())); connect(ui->actionExecute_script_at_server_side, SIGNAL(triggered()), room_scene, SLOT(doScript())); } else{ ui->menuCheat->setEnabled(false); ui->actionGet_card->disconnect(); ui->actionDeath_note->disconnect(); ui->actionDamage_maker->disconnect(); ui->actionRevive_wand->disconnect(); ui->actionSend_lowlevel_command->disconnect(); ui->actionExecute_script_at_server_side->disconnect(); } connect(room_scene, SIGNAL(restart()), this, SLOT(startConnection())); connect(room_scene, SIGNAL(return_to_start()), this, SLOT(gotoStartScene())); room_scene->adjustItems(); gotoScene(room_scene); }
void MainWindow::restartConnection(){ Self->deleteLater(); ClientInstance->deleteLater(); Self = NULL; ClientInstance = NULL; startConnection(); }
ClientNetworkDialog::ClientNetworkDialog(QWidget *parent) : QDialog(parent, Qt::Dialog) { setupUi(this); model = new P2PServiceModel(this); comboBox->setModel(model); connect(buttonBox, SIGNAL(accepted()), SLOT(startConnection())); connect(buttonBox, SIGNAL(rejected()), SLOT(reject())); }
/***************** * NetworkManager * *****************/ NetworkManager::NetworkManager(QString localPlayerId) : QObject(), m_server(NULL),m_NetworkLinkToServer(NULL),m_disconnectAsked(false),m_connectionState(false),m_localPlayer(NULL),m_audioPlayer(NULL),m_localPlayerId(localPlayerId) { m_reconnect = new QTimer(this); m_preferences = PreferencesManager::getInstance(); //m_thread = new ConnectionRetryThread(); m_dialog = new ConnectionRetryDialog(); connect(m_dialog,SIGNAL(tryConnection()),this,SLOT(startConnection())); connect(m_dialog,SIGNAL(rejected()),this,SIGNAL(stopConnectionTry())); }
OutgoingContactRequest::OutgoingContactRequest(ContactUser *u) : QObject(u), user(u), m_client(0) { emit user->identity->contacts.outgoingRequestAdded(this); attemptAutoAccept(); if (status() < FirstResult) { startConnection(); } }
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); scene = NULL; // initialize random seed for later use qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); connection_dialog = new ConnectionDialog(this); connect(ui->actionStart_Game, SIGNAL(triggered()), connection_dialog, SLOT(exec())); connect(connection_dialog, SIGNAL(accepted()), this, SLOT(startConnection())); config_dialog = new ConfigDialog(this); connect(ui->actionConfigure, SIGNAL(triggered()), config_dialog, SLOT(show())); connect(config_dialog, SIGNAL(bg_changed()), this, SLOT(changeBackground())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); StartScene *start_scene = new StartScene; QList<QAction*> actions; actions << ui->actionStart_Game << ui->actionStart_Server << ui->actionPC_Console_Start << ui->actionReplay << ui->actionConfigure << ui->actionGeneral_Overview << ui->actionCard_Overview << ui->actionScenario_Overview << ui->actionAbout << ui->actionAcknowledgement; foreach(QAction *action, actions) start_scene->addButton(action); view = new FitView(scene); setCentralWidget(view); restoreFromConfig(); gotoScene(start_scene); addAction(ui->actionShow_Hide_Menu); addAction(ui->actionFullscreen); addAction(ui->actionMinimize_to_system_tray); systray = NULL; }
static void requireCallback(BPErrorCode ec, void * cookie, const BPServiceDefinition ** , unsigned int , const char *, const char *) { BPProtoHand * pph = (BPProtoHand *) cookie; // done if (ec != BP_EC_OK) s_failures++; else s_complete++; BPFree(*pph); *pph = NULL; startConnection(pph); }
ConnectionError jConnection::connect() { if( !m_handler ) return ConnNotConnected; if(m_socket && (m_socket->state() == QAbstractSocket::ConnectedState || m_socket->state() == QAbstractSocket::ConnectingState) ) return ConnNoError; DEBUG() << Q_FUNC_INFO; // if(m_mutex_locker) // { // delete m_mutex_locker; // m_mutex_locker = 0; // } // m_mutex_locker = new QMutexLocker(&m_mutex); emit startConnection(); // QMutexLocker locker(&m_mutex); return m_error; }
DccChatWindow::DccChatWindow(DccDescriptor * dcc, const char * name) : DccWindow(KviWindow::DccChat, name, dcc) { m_pButtonBox = new KviTalHBox(this); m_pLabel = new KviThemedLabel(m_pButtonBox, this, "dcc_chat_label"); m_pLabel->setText(name); m_pButtonBox->setStretchFactor(m_pLabel, 1); m_pButtonContainer = new KviTalHBox(m_pButtonBox); createTextEncodingButton(m_pButtonContainer); #ifdef COMPILE_CRYPT_SUPPORT createCryptControllerButton(m_pButtonContainer); #endif m_pSplitter = new KviTalSplitter(Qt::Horizontal, this); m_pSplitter->setObjectName("dcc_chat_splitter"); m_pSplitter->setChildrenCollapsible(false); m_pIrcView = new KviIrcView(m_pSplitter, this); connect(m_pIrcView, SIGNAL(rightClicked()), this, SLOT(textViewRightClicked())); m_pInput = new KviInput(this); //setFocusHandler(m_pInput,this); m_pSlaveThread = nullptr; if(KVI_OPTION_BOOL(KviOption_boolAutoLogDccChat)) m_pIrcView->startLogging(); m_pMarshal = new DccMarshal(this); connect(m_pMarshal, SIGNAL(error(KviError::Code)), this, SLOT(handleMarshalError(KviError::Code))); connect(m_pMarshal, SIGNAL(connected()), this, SLOT(connected())); connect(m_pMarshal, SIGNAL(inProgress()), this, SLOT(connectionInProgress())); #ifdef COMPILE_SSL_SUPPORT connect(m_pMarshal, SIGNAL(startingSSLHandshake()), this, SLOT(startingSSLHandshake())); connect(m_pMarshal, SIGNAL(sslError(const char *)), this, SLOT(sslError(const char *))); #endif m_pSlaveThread = nullptr; startConnection(); }
void MainWindow::enterRoom(){ // add current ip to history if(!Config.HistoryIPs.contains(Config.HostAddress)){ Config.HistoryIPs << Config.HostAddress; Config.HistoryIPs.sort(); Config.setValue("HistoryIPs", Config.HistoryIPs); } ui->actionStart_Game->setEnabled(false); ui->actionStart_Server->setEnabled(false); RoomScene *room_scene = new RoomScene(this); ui->actionView_Discarded->setEnabled(true); ui->actionView_distance->setEnabled(true); ui->actionServerInformation->setEnabled(true); ui->actionKick->setEnabled(true); ui->actionSurrender->setEnabled(true); ui->actionSaveRecord->setEnabled(true); connect(ui->actionView_Discarded, SIGNAL(triggered()), room_scene, SLOT(toggleDiscards())); connect(ui->actionView_distance, SIGNAL(triggered()), room_scene, SLOT(viewDistance())); connect(ui->actionServerInformation, SIGNAL(triggered()), room_scene, SLOT(showServerInformation())); connect(ui->actionKick, SIGNAL(triggered()), room_scene, SLOT(kick())); connect(ui->actionSurrender, SIGNAL(triggered()), room_scene, SLOT(surrender())); connect(ui->actionSaveRecord, SIGNAL(triggered()), room_scene, SLOT(saveReplayRecord())); connect(ui->actionExpand_dashboard, SIGNAL(triggered()), room_scene, SLOT(adjustDashboard())); if(ServerInfo.FreeChoose){ ui->menuCheat->setEnabled(true); connect(ui->actionGet_card, SIGNAL(triggered()), ui->actionCard_Overview, SLOT(trigger())); connect(ui->actionDeath_note, SIGNAL(triggered()), room_scene, SLOT(makeKilling())); connect(ui->actionDamage_maker, SIGNAL(triggered()), room_scene, SLOT(makeDamage())); connect(ui->actionRevive_wand, SIGNAL(triggered()), room_scene, SLOT(makeReviving())); //modify by ce connect(ui->actionMp_maker, SIGNAL(triggered()), room_scene, SLOT(makeMp())); } connect(room_scene, SIGNAL(restart()), this, SLOT(startConnection())); gotoScene(room_scene); }
void TestNntpConnection::test_authenticate_ssl(){ iParams = new NntpServerParameters(cTestNntpServParamSSL()); iServer = new NntpServer(*iParams); iNntpCon = new NntpConnection(0, *iServer); connect(this, &TestNntpConnection::startConnection, iNntpCon, &Connection::startTcpConnection); // connect(iNntpCon, &NntpConnection::closed, this, &TestNntpConnection::closeConnection); // connect(iNntpCon, &Connection::socketError, this, &TestNntpConnection::handleSocketError); connect(iNntpCon, &NntpConnection::authenticated, this, &TestNntpConnection::inputAuthenticated); emit startConnection(iParams->name.toLatin1().constData(), iParams->port); QVERIFY(iNntpCon->doAuthentication()); delete iNntpCon; delete iServer; delete iParams; }
jConnection::jConnection( ConnectionDataHandler* cdh, const QString &profile_name, const QString &account_name ) : ConnectionBase(cdh), QObject(0) { m_profile_name = profile_name; m_account_name = account_name; m_error = ConnNotConnected; m_is_connecting = false; // m_mutex_locker = 0; m_current_host = 0; m_socket = 0; QObject::connect(this, SIGNAL(startConnection()), this, SLOT(atStartConnection())); m_use_dns_srv = false; loadProxySettings(); QSettings settings(QSettings::defaultFormat(), QSettings::UserScope, "qutim/qutim."+m_profile_name, "jabbersettings"); settings.beginGroup("main"); m_is_reconnect = settings.value("reconnect",true).toBool(); settings.endGroup(); m_reconnect_timer = new QTimer(); m_reconnect_timer->setInterval(5000); QObject::connect(m_reconnect_timer, SIGNAL(timeout()), this, SLOT(reconnect())); }
void runTest(unsigned int simulConns, long duration) { BPTime startTime; s_rl.init(); unsigned int i; std::cout << "running with " << simulConns << " simultaneous " << "connections for " << duration << "s." << std::endl; // setup a timer so we can stop the dance as configured StresserStopper ss; bp::time::Timer timer; timer.setListener(&ss); timer.setMsec(duration * 1000); // first allocate an array of connection handles BPProtoHand * s_phs = (BPProtoHand*) calloc(simulConns, sizeof(BPProtoHand)); // get all of the stress contexts connecting for (i=0; i<simulConns; i++) startConnection(s_phs + i); s_rl.run(); // now clean up and report for (i=0; i<simulConns; i++) BPFree(s_phs[i]); free(s_phs); s_phs = NULL; std::cout << "Test complete, " << s_started << " connections started, " << s_failures << " failures, " << s_complete << " completed. " << "Spent " << BPTime().diffInSeconds(startTime) << "s." << std::endl; }
int main(int argc, char **argv) { Client c; initGlobals(argc, argv); if (clientInit(&c) < 0) { fprintf(stderr, "ERROR: clientInit failed\n"); return -1; } // ok startup our connection to the server if (startConnection(&c, globals.host, globals.port, update_event_handler)<0) { fprintf(stderr, "ERROR: startConnection failed\n"); return -1; } shell(&c); return 0; }
void SocketServer::performConnect() { bool l_error; if( !SocketProtocol::waitSocketDataInfinite( listenSocket , l_error ) ) { continueConnecting = false; return; } // connect request received struct sockaddr_in clientAddress; memset( &clientAddress , 0 , sizeof( struct sockaddr_in ) ); clientAddress.sin_family = AF_INET; int l_len = sizeof( struct sockaddr_in ); SOCKET clientSocket = accept( listenSocket , ( struct sockaddr * )&clientAddress , &l_len ); if( clientSocket == INVALID_SOCKET ) { continueConnecting = false; logger.logError( "performConnect: accept returned INVALID_SOCKET" ); return; } /* set non-blocking */ unsigned long l_ok = 1; _ioctlsocket( clientSocket , FIONBIO , &l_ok ); /* set linger */ struct linger l_linger; l_linger.l_onoff = 1; l_linger.l_linger = 0; setsockopt( clientSocket , SOL_SOCKET , SO_LINGER , ( char * )&l_linger , sizeof( struct linger ) ); // start connection thread if( !startConnection( clientSocket , &clientAddress ) ) { continueConnecting = false; logger.logError( "performConnect: cannot start client thread" ); return; } }
int netGameStart() { int err=3; EnterCriticalSection(&netLock); if(isNetGame) err=4; else if(servername[0]) err= startConnection(); if(!err){ //connection succeeded isNetGame=true; DWORD id; ResumeThread(netGameThread=CreateThread(0, 0, netGameLoop, (void*)1, CREATE_SUSPENDED, &id)); } LeaveCriticalSection(&netLock); if(err==3){ //not connected, try listening err= startListen(); if(!err){ isListening=true; DWORD id; CloseHandle(CreateThread(0, 0, listenNetGame, 0, 0, &id)); } } return err; }
void Server::waitForClients() { // Variables struct sockaddr_in addrClient; socklen_t lenAddr; int fdClient; char buffAddr[12]; while(1) { // Loop where accepts and prints info about IP(inet_ntop). UserConnection can then print info for acceptted users. lenAddr = (socklen_t)sizeof(struct sockaddr_in); fdClient = accept(fdServerSocket, (struct sockaddr *) &addrClient, &lenAddr); if(fdClient == -1) printErr("Client connecting"); // Print info inet_ntop(AF_INET, (void *)&addrClient.sin_addr, buffAddr, 12); printf("User connected from: %s\n", buffAddr); // Start connection startConnection(fdClient); } }
const int FConnection::startConnection(const StringBuffer& aIAPName) { LOG.info("Starting new connection..."); LOG.debug("Looking for '%s' IAP name", aIAPName.c_str()); iLastError = KErrNone; StringBuffer errMsg; TCommDbConnPref prefs; prefs.SetDirection(ECommDbConnectionDirectionUnknown); if (aIAPName == "Default") { // // Use the default IAP without prompting the user // prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); prefs.SetIapId(0); } else if (aIAPName.empty() || aIAPName == "Ask") { // // Prompt user for IAP selection // } else { // // Search for the desired IAP. If not found, will prompt the user. // TInt iapID = GetIAPIDFromName(aIAPName); if (iapID >= 0) { LOG.debug("SetDialogPreference"); prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); prefs.SetIapId(iapID); } else { LOG.debug("IAP '%s' not found!", aIAPName.c_str()); } } /* * **** TODO: check if we need this! **** In S60 3rd Edition, enabling/disabling the inactivity timer will require the NetworkControl capability, which is only accessed via Symbian partner. */ //#if !defined(__SERIES60_3X__) || defined(__S60_3X_NET_CTRL__) // // Disable inactivity timer, otherwise inactive connection is closed // // within few seconds if there are no activity (e.g sockets) // iConnection.SetOpt(KCOLProvider, KConnDisableTimers, ETrue); //#endif // Opens the connection openConnection(); // Start connection iLastError = iConnection.Start(prefs); if (iLastError != KErrNone) { errMsg.sprintf("FConnection error: unable to start connection (code %d)", iLastError); LOG.debug("Goto retry"); goto retry; } // Save the IAP ID & name of the active connection. // Query the CommDb database for the IAP ID in use. _LIT(KIAPSettingName, "IAP\\Id"); iConnection.GetIntSetting(KIAPSettingName, iIAP); iIAPName = GetIAPNameFromID(iIAP); LOG.debug("Current active IAP ID = %d, name = '%s'", iIAP, iIAPName.c_str()); // // TODO: should we persist the iIAPName in the config, here? // iRetryConnection = 0; return 0; retry: LOG.error("%s", errMsg.c_str()); if (iIAPName.empty() || iIAPName == "Ask") { LOG.debug("Connection error and no IAP stored: don't retry"); return iLastError; } LOG.debug("About to retry..."); if (iRetryConnection < MAX_RETRY_CONNECTION) { iRetryConnection ++; LOG.info("Retry connection (%d time)...", iRetryConnection); startConnection(iIAPName); } else { LOG.error("FConnection: %d connection failed", iRetryConnection); } return iLastError; }
const int FConnection::startConnection() { return startConnection(iIAPName); }
void NsSmartDeviceLink::NsTransportManager::CTCPAdapter::mainThread(void) { LOG4CPLUS_INFO(mLogger, "Main thread initialized"); int socketFd = socket(AF_INET, SOCK_STREAM, 0); if (-1 != socketFd) { sockaddr_in serverAddress; memset(&serverAddress, 0, sizeof(serverAddress)); serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(cTCPAdapterPort); serverAddress.sin_addr.s_addr = INADDR_ANY; if (0 == bind(socketFd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) { if (0 == listen(socketFd, 128)) { while (false == mShutdownFlag) { sockaddr_in clientAddress; socklen_t clientAddressSize = sizeof(clientAddress); int connectionFd = accept(socketFd, (struct sockaddr*)&clientAddress, &clientAddressSize); if (connectionFd >= 0) { bool isConnectionThreadStarted = false; if ((AF_INET == clientAddress.sin_family) && (sizeof(clientAddress) == clientAddressSize)) { char deviceName[32]; strncpy(deviceName, inet_ntoa(clientAddress.sin_addr), sizeof(deviceName) / sizeof(deviceName[0])); LOG4CPLUS_INFO(mLogger, "Connected client " << deviceName); tDeviceHandle deviceHandle = InvalidDeviceHandle; pthread_mutex_lock(&mDevicesMutex); for (tDeviceMap::const_iterator deviceIterator = mDevices.begin(); deviceIterator != mDevices.end(); ++deviceIterator) { const STCPDevice * device = dynamic_cast<const STCPDevice *>(deviceIterator->second); if (0 != device) { if (clientAddress.sin_addr.s_addr == device->mAddress) { deviceHandle = deviceIterator->first; break; } } } pthread_mutex_unlock(&mDevicesMutex); if (InvalidDeviceHandle == deviceHandle) { deviceHandle = mHandleGenerator.generateNewDeviceHandle(); STCPDevice * device = new STCPDevice(deviceName, clientAddress.sin_addr.s_addr); pthread_mutex_lock(&mDevicesMutex); if (true == mDevices.insert(std::make_pair(deviceHandle, device)).second) { device->mUniqueDeviceId = std::string("TCP-") + deviceName; LOG4CPLUS_INFO(mLogger, "Added new device " << deviceHandle << ": " << device->mName << " (" << device->mUniqueDeviceId << ")"); } else { LOG4CPLUS_ERROR(mLogger, "Device handle " << deviceHandle << " is already present in devices map"); deviceHandle = InvalidDeviceHandle; delete device; device = 0; } pthread_mutex_unlock(&mDevicesMutex); if (0 != device) { updateClientDeviceList(); } } if (InvalidDeviceHandle != deviceHandle) { isConnectionThreadStarted = startConnection(new STCPConnection(deviceHandle, connectionFd, clientAddress.sin_port)); } else { LOG4CPLUS_ERROR(mLogger, "Failed to insert new device into devices map"); } } else { LOG4CPLUS_ERROR(mLogger, "Address of connected client is invalid"); } if (false == isConnectionThreadStarted) { close(connectionFd); } } else { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "accept() failed"); } } } else { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "listen() failed"); } } else { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "bind() failed"); } close(socketFd); } else { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "Failed to create socket"); } LOG4CPLUS_INFO(mLogger, "Main thread finished"); }
bool NetworkManager::configAndConnect(QString version) { bool isServer = !m_preferences->value("isClient",true).toBool(); bool isGM = !m_preferences->value("isPlayer",false).toBool(); int i=0; if(m_portStr.isEmpty()) { m_portStr = m_preferences->value("ServerPort",6660).toString(); } if(m_username.isEmpty()) { m_username = m_preferences->value("UserName",tr("UserName")).toString(); } if(m_host.isEmpty()) { m_host = m_preferences->value("ipaddress","").toString(); } else { isServer = false; } if(!m_role.isEmpty()) { isGM = m_role.compare("gm")==0 ? true : false; } m_configDialog = new ConnectionConfigDialog(NULL, m_username, m_preferences->value("UserColor",QColor(255,255,255)).value<QColor>(), isGM, m_host, m_portStr.toInt(), isServer); m_playersList = PlayersList::instance(); bool isConnected = false; m_configDialog->show();/// @warning prevent crash on windows. while((!isConnected) && (m_configDialog->exec() != QDialog::Rejected)) { m_isClient = !m_configDialog->isServer(); m_playersList->completeListClean(); if(m_localPlayer!=NULL) { delete m_localPlayer; m_localPlayer = NULL; } synchronizePreferences(); m_localPlayer = new Player( m_localPlayerId, m_configDialog->getName(), m_configDialog->getColor(), m_configDialog->isGM() ); m_localPlayer->setUserVersion(version); m_playersList->setLocalPlayer(m_localPlayer); isConnected = startConnection(); } return isConnected; }
/// /// \brief Client::Client /// \param parent /// constructor for the Client class Client::Client(QWidget *parent) : QDialog(parent), networkSession(0) { // Setting up widgets for the login window // set labels m_userLabel = new QLabel(tr("Email: ")); m_passwordLabel = new QLabel(tr("Password: "******"IP: ")); m_portLabel = new QLabel(tr("Port: ")); m_loginStatusLabel = new QLabel(tr("Please fill in IP and port and press Connect.")); // setup edits m_hostEdit = new QLineEdit; m_portEdit = new QLineEdit; m_portEdit->setValidator(new QIntValidator(1, 65535, this)); m_userEdit = new QLineEdit; m_passwordEdit = new QLineEdit; // connect labels to edits m_userLabel->setBuddy(m_userEdit); m_passwordLabel->setBuddy(m_passwordEdit); m_hostLabel->setBuddy(m_hostEdit); m_portLabel->setBuddy(m_portEdit); // setup buttons m_registerBtn = new QPushButton(tr("Register")); m_loginBtn = new QPushButton(tr("Log in")); m_connectBtn = new QPushButton(tr("Connect")); // initial button settings m_connectBtn->setDefault(true); //m_loginBtn->setEnabled(false); m_registerBtn->setEnabled(false); // button box buttonBox = new QDialogButtonBox; buttonBox->addButton(m_connectBtn, QDialogButtonBox::ActionRole); buttonBox->addButton(m_registerBtn, QDialogButtonBox::ActionRole); buttonBox->addButton(m_loginBtn, QDialogButtonBox::ActionRole); // connect button press signals to slots connect(m_connectBtn, SIGNAL(clicked()), this, SLOT(startConnection())); connect(m_registerBtn, SIGNAL(clicked()), this, SLOT(registerUser())); connect(m_loginBtn, SIGNAL(clicked()), this, SLOT(login())); // read from server when server sends data m_tcpSocket = new QTcpSocket(this); connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(readServerResponse())); connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); // put widgets on a window //QGridLayout *loginLayout = new QGridLayout; loginLayout.addWidget(m_hostLabel, 0, 0); loginLayout.addWidget(m_hostEdit, 0, 1); loginLayout.addWidget(m_portLabel, 1, 0); loginLayout.addWidget(m_portEdit, 1, 1); loginLayout.addWidget(m_userLabel, 2, 0); loginLayout.addWidget(m_userEdit, 2, 1); loginLayout.addWidget(m_passwordLabel, 3, 0); loginLayout.addWidget(m_passwordEdit, 3, 1); loginLayout.addWidget(m_loginStatusLabel, 4, 0, 1, 2); loginLayout.addWidget(buttonBox, 5, 0, 1, 2); setLayout(&loginLayout); // set up the inbox m_inbox = new QListWidget(); QObject::connect(m_inbox, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(viewMessage(QListWidgetItem*))); m_inbox->setStyleSheet("QListWidget::item{border-bottom:1px solid black;}"); m_viewingSent = 0; // test code for setting up emails Email* e1 = new Email(); e1->setFrom("John"); e1->setSubject("money"); e1->setMessage("Yo n***a, you betta give me my money!"); e1->setRead(false); e1->setText(e1->getFrom() + " | " + e1->getSubject()); e1->setData(12, 1); e1->setID(1); Email* e2 = new Email(); e2->setFrom("Simon"); e2->setSubject("hangout"); e2->setMessage("Hey man, do you want to hangout?"); e2->setRead(false); e2->setText(e2->getFrom() + " | " + e2->getSubject()); m_emails.append(e1); m_emails.append(e2); e2->setData(12, 2); e2->setID(2); }
static void reconnectServer(evutil_socket_t fd, short event, void* args) { DEBUG(255, "reconnectServer(%d, 0x%02x, %p);", fd, event, args); struct reconnect_struct* reconnect_struct = (struct reconnect_struct*) args; startConnection(reconnect_struct->server, reconnect_struct->base); free(reconnect_struct); };
DccVoiceWindow::DccVoiceWindow(DccDescriptor * dcc,const char * name) : DccWindow(KviWindow::DccVoice,name,dcc) { m_pDescriptor = dcc; m_pSlaveThread = 0; m_pSplitter = new KviTalSplitter(Qt::Horizontal,this); m_pSplitter->setObjectName("dcc_window_splitter"); m_pIrcView = new KviIrcView(m_pSplitter,this); m_pHBox = new KviTalHBox(this); KviTalVBox * vbox = new KviTalVBox(m_pHBox); m_pInputLabel = new QLabel(__tr2qs_ctx("Input buffer","dcc"),vbox); m_pInputLabel->setFrameStyle(QFrame::Sunken | QFrame::Panel); m_pOutputLabel = new QLabel(__tr2qs_ctx("Output buffer","dcc"),vbox); m_pOutputLabel->setFrameStyle(QFrame::Sunken | QFrame::Panel); vbox->setSpacing(1); KviTalVBox * vbox2 = new KviTalVBox(m_pHBox); m_pRecordingLabel = new QLabel(vbox2); m_pRecordingLabel->setPixmap(*(g_pIconManager->getSmallIcon(KviIconManager::Record))); m_pRecordingLabel->setEnabled(false); m_pRecordingLabel->setFrameStyle(QFrame::Raised | QFrame::Panel); m_pPlayingLabel = new QLabel(vbox2); m_pPlayingLabel->setPixmap(*(g_pIconManager->getSmallIcon(KviIconManager::Play))); m_pPlayingLabel->setEnabled(false); m_pPlayingLabel->setFrameStyle(QFrame::Raised | QFrame::Panel); vbox2->setSpacing(1); //#warning "The volume slider should be enabled only when receiving data" //m_pVolumeSlider = new QSlider(-100, 0, 10, 0, Qt::Vertical, m_pHBox, "dcc_voice_volume_slider"); m_pVolumeSlider = new QSlider(Qt::Vertical,m_pHBox); m_pVolumeSlider->setObjectName("dcc_voice_volume_slider"); m_pVolumeSlider->setMinimum(-100); m_pVolumeSlider->setMaximum(0); m_pVolumeSlider->setPageStep(10); m_pVolumeSlider->setValue(0); m_pVolumeSlider->setValue(getMixerVolume()); /* Update the tooltip */ setMixerVolume(m_pVolumeSlider->value()); m_pVolumeSlider->setMaximumWidth(16); m_pVolumeSlider->setMaximumHeight(2*m_pPlayingLabel->height()); connect(m_pVolumeSlider, SIGNAL(valueChanged(int)), this, SLOT(setMixerVolume(int))); m_pTalkButton = new QToolButton(m_pHBox); m_pTalkButton->setEnabled(false); m_pTalkButton->setCheckable(true); QIcon iset; iset.addPixmap(*(g_pIconManager->getBigIcon(KVI_BIGICON_DISCONNECTED)),QIcon::Normal,QIcon::Off); iset.addPixmap(*(g_pIconManager->getBigIcon(KVI_BIGICON_CONNECTED)),QIcon::Normal,QIcon::On); m_pTalkButton->setIcon(iset); m_pTalkButton->setIconSize(QSize(32,32)); connect(m_pTalkButton,SIGNAL(toggled(bool)),this,SLOT(startOrStopTalking(bool))); m_pHBox->setStretchFactor(vbox,1); m_pHBox->setMargin(2); m_pHBox->setSpacing(1); //setFocusHandler(m_pIrcView,this); m_pMarshal = new DccMarshal(this); connect(m_pMarshal,SIGNAL(error(KviError::Code)),this,SLOT(handleMarshalError(KviError::Code))); connect(m_pMarshal,SIGNAL(connected()),this,SLOT(connected())); connect(m_pMarshal,SIGNAL(inProgress()),this,SLOT(connectionInProgress())); m_pUpdateTimer = new QTimer(); startConnection(); }
So2sdrBandmap::So2sdrBandmap(QStringList args, QWidget *parent) : QMainWindow(parent) { setupUi(this); initPointers(); initVariables(); // check to see if user directory exists initialized = checkUserDirectory(); settingsFile = userDirectory()+"/so2sdr-bandmap.ini"; // check for optional command argument giving station config file name if (args.size() > 1) { settingsFile = args[1].trimmed(); // Qt doesn't understand that ~/... implies home directory... if (settingsFile.left(1)=="~") { if (settingsFile.left(2)=="~/") { settingsFile=QDir::homePath()+settingsFile.right(settingsFile.size()-1); } else { // for cases like ~name : no easy way to parse, give up QMessageBox msgBox; msgBox.setText("Please use the complete path to the settings file."); msgBox.setInformativeText(settingsFile); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); close(); } } } QFileInfo fi(settingsFile); if (!fi.exists()) { QMessageBox msgBox; msgBox.setText("The settings file "+settingsFile+" does not exist."); msgBox.setInformativeText("Do you want to create it?"); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); if (msgBox.exec()==QMessageBox::Cancel) { close(); } firstTime=true; } settings = new QSettings(settingsFile,QSettings::IniFormat,this); if (settings->status()!=QSettings::NoError) { errorBox.showMessage("ERROR: problem starting qsettings"); } // if run the first time with default settings file for second radio, // set second radio if (firstTime && settingsFile.right(19)=="so2sdr-bandmap2.ini") { settings->setValue(s_sdr_nrig,1); } // restore window size and position QString tmp="BandmapWindow"; settings->beginGroup(tmp); resize(settings->value("size", QSize(400, 594)).toSize()); move(settings->value("pos", QPoint(200, 200)).toPoint()); settings->endGroup(); directory.setCurrent(dataDirectory()); setWindowIcon(QIcon("icon24x24.png")); if (settings->value(s_sdr_reverse_scroll,s_sdr_reverse_scroll_def).toBool()) { horizontalLayout->removeWidget(CallLabel); horizontalLayout->removeWidget(FreqLabel); horizontalLayout->removeWidget(display); horizontalLayout->insertWidget(0,CallLabel); horizontalLayout->insertWidget(1,FreqLabel); horizontalLayout->insertWidget(2,display); } freqPixmap = QPixmap(FreqLabel->width(), settings->value(s_sdr_fft,s_sdr_fft_def).toInt()); callPixmap = QPixmap(CallLabel->width(), settings->value(s_sdr_fft,s_sdr_fft_def).toInt()); ipAddress= QHostAddress(QHostAddress::LocalHost).toString(); if (!server.listen(QHostAddress::LocalHost, settings->value(s_sdr_bandmap_tcp_port,s_sdr_bandmap_tcp_port_def).toInt())) { qDebug("couldn't start tcp server"); } connect(&server, SIGNAL(newConnection()), this, SLOT(startConnection())); setFocusPolicy(Qt::StrongFocus); setFocusPolicy(Qt::NoFocus); display->setFocusPolicy(Qt::NoFocus); CallLabel->setFocusPolicy(Qt::NoFocus); FreqLabel->setFocusPolicy(Qt::NoFocus); checkBoxMark.setText("Mark"); checkBoxMark.setToolTip("Enables signal detection."); toolBar->setMovable(false); QWidget* spacer1 = new QWidget(); spacer1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); toolBar->addWidget(spacer1); toolBar->addWidget(&checkBoxMark); txLabel.clear(); txLabel.setText("<font color=#000000>TX"); toolBar->addWidget(&txLabel); slider.setToolTip("Gain for signal detection. To the right is LESS sensitive."); slider.setOrientation(Qt::Horizontal); connect(&slider,SIGNAL(valueChanged(int)),this,SLOT(updateLevel(int))); slider.setFixedWidth(60); slider.setMaximum(200); slider.setMinimum(0); slider.setSingleStep(10); slider.setPageStep(50); slider.setValue(settings->value(s_sdr_level,s_sdr_level_def).toInt()); toolBar->addWidget(&slider); QWidget* spacer2 = new QWidget(); spacer2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); toolBar->addWidget(spacer2); toolBar->addAction("&Help",this,SLOT(showHelp())); iqDialog = new IQBalance(this, Qt::Window); iqDialog->clearPlots(); showToolBar = new QAction("&toolbar",this); scaleX1 = new QAction("Zoom x&1", this); scaleX2 = new QAction("Zoom x&2", this); deleteAct = new QAction("&Delete Call", this); checkBoxMark.setChecked(settings->value(s_sdr_peakdetect,s_sdr_peakdetect_def).toBool()); iqShowData = new QAction("IQ Balance", this); connect(iqShowData, SIGNAL(triggered()), this, SLOT(showIQData())); connect(&checkBoxMark, SIGNAL(clicked()), this, SLOT(emitParams())); connect(deleteAct, SIGNAL(triggered()), this, SLOT(deleteCallMouse())); showToolBar->setCheckable(true); showToolBar->setChecked(true); connect(showToolBar,SIGNAL(triggered(bool)),this,SLOT(setShowToolbar(bool))); scaleX1->setCheckable(true); scaleX2->setCheckable(true); scaleX2->setChecked(false); scaleX1->setChecked(true); connect(scaleX1, SIGNAL(triggered()), this, SLOT(setScaleX1())); connect(scaleX2, SIGNAL(triggered()), this, SLOT(setScaleX2())); connect(actionRun,SIGNAL(triggered()),this,SLOT(start())); sdrSetup = new SDRDialog(*settings,this); connect(actionSetup,SIGNAL(triggered()),sdrSetup,SLOT(show())); connect(actionSetup,SIGNAL(triggered()),this,SLOT(disconnectSignals())); connect(sdrSetup,SIGNAL(setupErrors(QString)),&errorBox,SLOT(showMessage(QString))); connect(sdrSetup,SIGNAL(update()),this,SLOT(setSdrType())); connect(sdrSetup,SIGNAL(restartSdr()),this,SLOT(restartSdr())); connect(display, SIGNAL(displayMouseQSY(int)), this, SLOT(mouseQSYDelta(int))); toolBarHeight = toolBar->height(); // select type of SDR, create data source sdrSource spectrumProcessor = new Spectrum(this,*settings,userDirectory()); switch ((SdrType)settings->value(s_sdr_type,s_sdr_type_def).toInt()) { case soundcard_t: sdrSource = new AudioReaderPortAudio(settingsFile); break; case afedri_t: sdrSource = new Afedri(settingsFile); break; case network_t: sdrSource = new NetworkSDR(settingsFile); break; } setSdrType(); sdrSource->moveToThread(&sdrThread); connect(actionSetup,SIGNAL(triggered()),sdrSource,SLOT(stop()),Qt::DirectConnection); connect(&sdrThread,SIGNAL(started()),sdrSource,SLOT(initialize())); connect(sdrSource,SIGNAL(stopped()),&sdrThread,SLOT(quit())); connect(sdrSource,SIGNAL(stopped()),this,SLOT(disconnectSignals())); connect(sdrSource,SIGNAL(error(QString)),&errorBox,SLOT(showMessage(QString))); connect(spectrumProcessor, SIGNAL(spectrumReady(unsigned char*, unsigned char)), display, SLOT(plotSpectrum(unsigned char*, unsigned char))); connect(sdrSource, SIGNAL(ready(unsigned char *, unsigned char)),spectrumProcessor, SLOT(processData(unsigned char *, unsigned char)),Qt::QueuedConnection); connect(iqDialog, SIGNAL(closed(bool)), spectrumProcessor, SLOT(setPlotPoints(bool))); connect(iqDialog, SIGNAL(restart()), spectrumProcessor, SLOT(clearIQ())); connect(spectrumProcessor, SIGNAL(qsy(int)), this, SLOT(findQsy(int))); connect(spectrumProcessor, SIGNAL(clearPlot()), iqDialog, SLOT(clearPlots())); connect(spectrumProcessor, SIGNAL(gainPoint(int, double)), iqDialog, SLOT(plotGainPoint(int, double))); connect(spectrumProcessor, SIGNAL(phasePoint(int, double)), iqDialog, SLOT(plotPhasePoint(int, double))); connect(spectrumProcessor, SIGNAL(gainScale(double, double)), iqDialog, SLOT(setGainScale(double, double))); connect(spectrumProcessor, SIGNAL(phaseScale(double, double)), iqDialog, SLOT(setPhaseScale(double, double))); connect(spectrumProcessor, SIGNAL(plotGainFunc(double, double, double, double)), iqDialog, SLOT(plotGainFunc(double, double, double, double))); connect(spectrumProcessor, SIGNAL(plotPhaseFunc(double, double, double, double)), iqDialog, SLOT(plotPhaseFunc(double, double, double, double))); // vfoPos is the position of the red line indicating center vfoPos = (height()-toolBarHeight)/ 2; dragPos = vfoPos; display->setVfoPos(vfoPos); makeFreqScaleAbsolute(); FreqLabel->setPixmap(freqPixmap); FreqLabel->update(); startTimers(); show(); }
void NsSmartDeviceLink::NsTransportManager::CTCPAutoconnectAdapter::mainThread(void) { LOG4CPLUS_TRACE_METHOD(mLogger, __PRETTY_FUNCTION__); int socketFd; sockaddr_in serverAddress; mBoundPortNumber = TCP_AUTOCONNECT_INITIAL_PORT; while (!mShutdownFlag) { socketFd = socket(AF_INET, SOCK_STREAM, 0); if (socketFd == -1) { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "Could not create socket!"); return; } const int on = 1; if (-1 == setsockopt(socketFd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "setsockopt failed!"); } if (-1 == fcntl(socketFd, F_SETFD, FD_CLOEXEC)) { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "FD_CLOEXEC failed!"); } bzero(&serverAddress, sizeof(serverAddress)); serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(mBoundPortNumber); if (0 != bind(socketFd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "bind() failed!"); close(socketFd); mBoundPortNumber ++; } if (0 != listen(socketFd, MAX_CONNECTIONS)) { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "listen() failed!"); close(socketFd); mBoundPortNumber ++; } else { LOG4CPLUS_INFO(mLogger, "Bound to " << mBoundPortNumber << " successfully!"); break; } } if (mShutdownFlag) { LOG4CPLUS_INFO(mLogger, "Thread has been stopped while binding!"); return; } startBroadcastThread(); while (false == mShutdownFlag) { sockaddr_in clientAddress; socklen_t clientAddressSize = sizeof(clientAddress); int connectionFd = accept(socketFd, (struct sockaddr*)&clientAddress, &clientAddressSize); if (connectionFd >= 0) { bool isConnectionThreadStarted = false; if ((AF_INET == clientAddress.sin_family) && (sizeof(clientAddress) == clientAddressSize)) { char deviceName[32]; strncpy(deviceName, inet_ntoa(clientAddress.sin_addr), sizeof(deviceName) / sizeof(deviceName[0])); LOG4CPLUS_INFO(mLogger, "Connected client " << deviceName); tDeviceHandle deviceHandle = InvalidDeviceHandle; pthread_mutex_lock(&mDevicesMutex); for (tDeviceMap::const_iterator deviceIterator = mDevices.begin(); deviceIterator != mDevices.end(); ++deviceIterator) { const STCPDevice * device = dynamic_cast<const STCPDevice *>(deviceIterator->second); if (0 != device) { if (clientAddress.sin_addr.s_addr == device->mAddress) { deviceHandle = deviceIterator->first; break; } } } pthread_mutex_unlock(&mDevicesMutex); if (InvalidDeviceHandle == deviceHandle) { deviceHandle = mHandleGenerator.generateNewDeviceHandle(); STCPDevice * device = new STCPDevice(deviceName, clientAddress.sin_addr.s_addr); pthread_mutex_lock(&mDevicesMutex); if (true == mDevices.insert(std::make_pair(deviceHandle, device)).second) { device->mUniqueDeviceId = std::string("TCP-") + deviceName; LOG4CPLUS_INFO(mLogger, "Added new device " << deviceHandle << ": " << device->mName << " (" << device->mUniqueDeviceId << ")"); } else { LOG4CPLUS_ERROR(mLogger, "Device handle " << deviceHandle << " is already present in devices map"); deviceHandle = InvalidDeviceHandle; delete device; device = 0; } pthread_mutex_unlock(&mDevicesMutex); if (0 != device) { updateClientDeviceList(); } } if (InvalidDeviceHandle != deviceHandle) { isConnectionThreadStarted = startConnection(new STCPConnection(deviceHandle, connectionFd, clientAddress.sin_port)); } else { LOG4CPLUS_ERROR(mLogger, "Failed to insert new device into devices map"); } } else { LOG4CPLUS_ERROR(mLogger, "Address of connected client is invalid"); } if (false == isConnectionThreadStarted) { close(connectionFd); } } else { LOG4CPLUS_ERROR_WITH_ERRNO(mLogger, "accept() failed"); } } // connect loop end pthread_join(mBroadcastThread, 0); }