int main(int argc, char *argv[]) { QApplication a(argc, argv); // Get the port we will listen on QInputDialog options; options.setLabelText("Enter port for listening:"); options.setTextValue("12349"); options.exec(); MainWindow window; Server server(options.textValue()); Client client; window.connect(&server, SIGNAL(messageRecieved(QString,QString)), &window, SLOT(displayNewMessage(QString,QString))); window.connect(&window, SIGNAL(connectToChanged(QString,QString)), &client, SLOT(connectTo(QString,QString))); window.connect(&window, SIGNAL(sendMessage(QString)), &client, SLOT(startTransfer(QString))); window.show(); window.resize(480,320); window.setWindowTitle(window.windowTitle() + " (listen port: " + options.textValue() + ")"); return a.exec(); }
void QAMQP::Network::error( QAbstractSocket::SocketError socketError ) { if(timeOut_ == 0) { timeOut_ = 1000; } else { if(timeOut_ < 120000) { timeOut_ *= 5; } } Q_UNUSED(socketError); switch(socketError) { case QAbstractSocket::ConnectionRefusedError: case QAbstractSocket::RemoteHostClosedError: case QAbstractSocket::SocketTimeoutError: case QAbstractSocket::NetworkError: case QAbstractSocket::ProxyConnectionClosedError: case QAbstractSocket::ProxyConnectionRefusedError: case QAbstractSocket::ProxyConnectionTimeoutError: default: qWarning() << "AMQP: Socket Error: " << socket_->errorString(); emit error(socket_->errorString()); break; } if( autoReconnect_ && connect_ ) { QTimer::singleShot(timeOut_, this, SLOT(connectTo())); } }
Arc::Socket::Socket( IPAddress address, unsigned int port, SocketType type ) : _socket(INVALID_SOCKET), _error(false), _errorMsg() { connectTo(address, port, type); }
Arc::Socket::Socket( string hostname, unsigned int port, SocketType type ) : _socket(INVALID_SOCKET), _error(false), _errorMsg() { connectTo(hostname, port, type); }
int main(int argc, char** argv) { int n, fd; long dec, enc; struct Arguments args; pthread_t readThread, writeThread; long a, b; // two prime numbers if(argc < 5) { printf("file portNum hostName prime1 prime2\n"); exit(0); } a = atoi(argv[3]) + 6; b = atoi(argv[4]) + 6; generatePrimeNumbers(&a, &b); generateKeys(a, b, &args.my_e, &args.my_d, &args.my_c); args.run = 1; fd = connectTo(argv[2], atoi(argv[1])); args.connfd = fd; sendKeys(&args); receiveKeys(&args); pthread_create(&readThread, NULL, readData, &args); pthread_create(&writeThread, NULL, writeData, &args); pthread_join(readThread, NULL); pthread_cancel(writeThread); close(fd); }
AREXPORT bool ArSocket::connectTo(const char *host, int port) { char localhost[MAXGETHOSTSTRUCT]; if (myFD < 0) return(false); if (!host) { if (gethostname(localhost, sizeof(localhost)) == 1) { myErrorStr="Failure to locate host '"; myErrorStr+=localhost; myErrorStr+="'"; perror("gethostname"); return(false); } host=localhost; } memset(&mySin, 0, sizeof(mySin)); if (!hostAddr(host, mySin.sin_addr)) return(false); setIPString(); mySin.sin_family=AF_INET; mySin.sin_port=hostToNetOrder(port); return(connectTo(&mySin)); }
/** @return false and set error code and description string on failure */ bool ArSocket::connectTo(const char *host, int port) { char localhost[maxHostNameLen()]; myError = NoErr; myErrorStr.clear(); if (myFD < 0) return(false); if (!host) { if (gethostname(localhost, sizeof(localhost)) == 1) { myErrorStr="Failure to locate host '"; myErrorStr+=localhost; myErrorStr+="'"; perror("gethostname"); return(false); } host=localhost; } char useHost[1024]; int usePort; separateHost(host, port, useHost, sizeof(useHost), &usePort); bzero(&mySin, sizeof(mySin)); if (!hostAddr(useHost, mySin.sin_addr)) return(false); setRawIPString(); mySin.sin_family=AF_INET; mySin.sin_port=hostToNetOrder(usePort); return(connectTo(&mySin)); }
bool ArSocket::connectTo(const char *host, int port) { char localhost[100]; // maxHostNameLen()]; if (myFD < 0) return(false); if (!host) { if (gethostname(localhost, sizeof(localhost)) == 1) { myErrorStr="Failure to locate host '"; myErrorStr+=localhost; myErrorStr+="'"; perror("gethostname"); return(false); } host=localhost; } bzero(&mySin, sizeof(mySin)); if (!hostAddr(host, mySin.sin_addr)) return(false); setIPString(); mySin.sin_family=AF_INET; mySin.sin_port=hostToNetOrder(port); return(connectTo(&mySin)); }
int Client::terminate() const { int sfd = connectTo(binderHost, binderPort); if (sfd < 0) { return sfd; } Connection conn(sfd); return conn.send(Message::Type::TERMINATION, ""); }
void WidgetIrcMain::connectTo(const QString& host, quint16 port, const QString& nick, const QString& password) { ConnectionInfo conn; conn.host = host; conn.port = port; conn.nick = nick; conn.pass = password; connectTo(conn); }
Sock::status_t Sock::connectTo(const char* hostname, unsigned int port, int& sock) { int rc = create(PF_INET, SOCK_STREAM, 0, sock); if (rc != SUCCESS) return ERR_SOCK_CREATE; return connectTo(sock, hostname, port); }
void gCommandLineJumpStartAnalyzer::Connect() { tString server; tString port; ExtractConnectionInformation( _raw, server, port ); nServerInfoRedirect connectTo( server, port.ToInt() ); ConnectToServer( &connectTo ); }
int Client::connectToServer(const FunctionSignature& signature) const { int binderSocket = connectTo(binderHost, binderPort); if (binderSocket < 0) { return binderSocket; } Connection binderConnection(binderSocket); // Send a request for the server address binderConnection.send(Message::Type::ADDRESS, signature.serialize()); // Read the response for the server address Message message; if (binderConnection.read(&message) < 0 || message.type != Message::Type::ADDRESS) { binderConnection.close(); return -1; } binderConnection.close(); // Okay, now we have the message with the server address auto serverAddress = ServerAddress::deserialize(message); return connectTo(serverAddress.hostname, serverAddress.port); }
void ServerListDialog::slotOk() { QPtrList<QListViewItem> selected = m_serverList->selectedItems(); ServerListItem * item = static_cast<ServerListItem*>(selected.first()); while (item) { if (item->isServer()) { ConnectionSettings settings; settings.setServerGroup(Preferences::serverGroupById(item->serverGroupId())); settings.setServer(item->server()); emit connectTo(Konversation::PromptToReuseConnection, settings); } else emit connectTo(Konversation::PromptToReuseConnection, item->serverGroupId()); item = static_cast<ServerListItem*>(selected.next()); } }
void *request(void* arg) { unsigned long delay = *((unsigned*)arg); long st, duration; int sock, reply; counter++; st = time_millis(); sock = connectTo(load_balancer, PORT_LB); write(sock, &counter, sizeof(int)); read(sock, &reply, sizeof(int)); close(sock); duration = time_millis() - st; printf("%ld %lu %ld %d\n", st, delay, duration, reply); }
/** @return false and set error code and description string on failure */ AREXPORT bool ArSocket::connectTo(const char *host, int port) { char localhost[MAXGETHOSTSTRUCT]; myError = NoErr; myErrorStr.clear(); if (myFD == INVALID_SOCKET) return(false); if (!host) { if (gethostname(localhost, sizeof(localhost)) == 1) { myErrorStr="Failure to locate host '"; myErrorStr+=localhost; myErrorStr+="'"; myError = ConBadHost; ArLog::logErrorFromOS(ArLog::Normal, "ArSocket::connectTo: gethostname failed"); return(false); } host=localhost; } char useHost[1024]; int usePort; separateHost(host, port, useHost, sizeof(useHost), &usePort); //myHost = ((host != NULL) ? host : ""); //myPort = port; myHost = useHost; myPort = usePort; memset(&mySin, 0, sizeof(mySin)); if (!hostAddr(useHost, mySin.sin_addr)) { myError = ConBadHost; return(false); } setRawIPString(); mySin.sin_family=AF_INET; mySin.sin_port=hostToNetOrder(usePort); return(connectTo(&mySin)); }
int main(int argc, char *argv[]) { int workers_n = atoi(argv[1]); //number of workers char *hostnames = argv[2]; //comma separated list of workers' hostnames int iteration = atoi(argv[3]); // iteration counter. char *token; //for hosts tokenization char* hosts[workers_n], *host_name; //workers' socket names int sock; //socket descriptor int data; pid_t pid; int listenfd = 0, connfd = 0, counter = 0; struct sockaddr_in serv_addr; long st, et; data = 0; token = strtok(hostnames, ","); while (token != NULL ) { hosts[data++] = token; token = strtok(NULL, ","); } socketlisten(&listenfd, atoi(PORT_LB)); fflush(stdout); while (1) { host_name = hosts[counter]; counter = counter == workers_n - 1 ? 0 : counter + 1; fprintf(stderr, "next worker: %s\n", host_name); connfd = accept(listenfd, (struct sockaddr*) NULL, NULL ); if (!(pid = fork())) { fprintf(stderr, "connection at %ld\n", time_millis()); st = time_millis(); read(connfd, &data, sizeof(data)); sock = connectTo(host_name, PORT, "to worker"); write(sock, &data, sizeof(data)); read(sock, &data, sizeof(data)); write(connfd, &data, sizeof(data)); et = time_millis(); fprintf(stdout, "%d %ld %ld %s\n", iteration, st, et, host_name); return 0; } else { if (pid == -1) fprintf(stderr, "ERROR creating process: %d\n", errno); } } }
void ConnectionManager::connectTo(Konversation::ConnectionFlag flag, int serverGroupId) { ConnectionSettings settings; Konversation::ServerGroupSettingsPtr serverGroup; serverGroup = Preferences::serverGroupById(serverGroupId); if (serverGroup) { settings.setServerGroup(serverGroup); if (serverGroup->serverList().size() > 0) settings.setServer(serverGroup->serverList()[0]); } connectTo(flag, settings); }
void ProtocolDataTransfer::run() { switch (m_SocketMode) { case Slave: if (accept() == -1) { return; } break; case Active: if (connectTo() == -1) { return; } break; default: return; } switch (m_Protocol) { case DoSendFile: sendFile(); break; case DoRecvFile: recvFile(); break; case DoSendDir: sendDir(); break; case DoRecvDir: recvDir(); break; case DoSendList: sendList(); break; case DoRecvList: recvList(); break; } }
/* Main function that also spawns the thread */ int main(int argc, char** argv) { srand(time(NULL)); pthread_t readThread, writeThread; struct Parameters args; int connfd; long first_prime, sec_prime, e, c, d; if(argc < 3) { printf("Run client with 'client [host name] [port number]'\n"); exit(0); } char host[20]; strcpy(host, argv[1]); connfd = connectTo(host, atoi(argv[2])); printf("\nEnter two numbers (m n) to generate keys based on the mth and nth primes: "); scanf("%ld %ld", &first_prime, &sec_prime); printf("\nGenerating keys...\n"); generatePrimeNumbers(&first_prime, &sec_prime); generateKeys(first_prime, sec_prime, &e, &d, &c); printf("Your public key (will be sent to server): %ld %ld\n", e, c); printf("Your private key (will not be sent): %ld %ld\n", d, c); args.connfd = connfd; args.clientE = e; args.clientN = c; args.clientD = d; receive_key(&args); send_key(&args); pthread_create(&writeThread, NULL, write_data, &args); pthread_create(&readThread, NULL, read_data, &args); pthread_join(writeThread, NULL); pthread_join(readThread, NULL); close(connfd); exit(0); }
//XXX should the "free" free the names that these ports point too as well? void JackCpp::AudioIO::connectToPhysical(unsigned int index, unsigned physical_index) throw(std::range_error, std::runtime_error) { const char **ports; if (mJackState != active) throw std::runtime_error("client must be active before connecting ports"); if (index > mOutputPorts.size()) throw std::range_error("outport index out of range"); ports = jack_get_ports (mJackClient, NULL, NULL, JackPortIsPhysical|JackPortIsInput); if(ports == NULL){ throw std::range_error("no physical inports to connect to"); } //make sure the port exists for(unsigned int i = 0; i <= physical_index; i++){ if(ports[i] == NULL){ free(ports); throw std::range_error("physical inport index out of range"); } } connectTo(index, ports[physical_index]); free(ports); }
void ConnectionManager::connectTo(Konversation::ConnectionFlag flag, const QList<KUrl>& list) { QMap<QString,Konversation::ChannelList> serverChannels; QMap<QString,ConnectionSettings> serverConnections; QList<KUrl>::ConstIterator it = list.constBegin(); QList<KUrl>::ConstIterator end = list.constEnd(); for (; it != end; ++it) { ConnectionSettings settings; decodeIrcUrl(it->url(), settings); kDebug() << settings.name() << " - " << settings.server().host() << settings.server().port() << settings.server().password() << " - " << (settings.serverGroup()?settings.serverGroup()->name():""); QString sname = (settings.serverGroup() ? settings.serverGroup()->name() : (QString(settings.server().host()) + QString(':') + QString(settings.server().port()))); if (!serverChannels.contains(sname)) serverConnections[sname] = settings; serverChannels[sname] += settings.oneShotChannelList(); } // Perform the connection. QMap<QString,Konversation::ChannelList>::ConstIterator s_i = serverChannels.constBegin(); for (; s_i != serverChannels.constEnd(); ++s_i) { serverConnections[s_i.key()].setOneShotChannelList(s_i.value()); connectTo(flag, serverConnections[s_i.key()]); } }
void connectToPeers(struct peerlist* plist) { struct peerlist* ptr = plist; struct peerlist* tmp; while(ptr != NULL) { int connection_fd = connectTo(ptr->hostname, ptr->port); /* Send 1 record linkstate packet, * with RTT of 1 and ID of current time */ struct LinkStateNode self_lstate; self_lstate.ID = getTime(); self_lstate.avg_RTT = 1; self_lstate.next = NULL; struct AddressInfo local, remote; if(getLocalAddrInfo(connection_fd, &local) == -1){ fprintf(stderr, "Could not get local info. Error Code: %d", connection_fd); exit(EXIT_FAILURE); } if(getRemoteAddrInfo(connection_fd, &remote) == -1){ fprintf(stderr, "Could not get remote info. Error Code: %d", connection_fd); exit(EXIT_FAILURE); } self_lstate.local = local; self_lstate.remote = remote; /* Send 1 record linkstate packet of end peer */ sendPacketToSock((void*)&self_lstate,connection_fd); tmp = ptr; ptr = ptr->next; free(tmp); } }
void ConnectionManager::connectTo(Konversation::ConnectionFlag flag, const QString& target, const QString& port, const QString& password, const QString& nick, const QString& channel, bool useSSL) { ConnectionSettings settings; if (target.startsWith(QLatin1String("irc://")) || target.startsWith(QLatin1String("ircs://"))) decodeIrcUrl(target, settings); else { decodeAddress(target, settings); Konversation::ServerSettings server = settings.server(); if (!port.isEmpty()) server.setPort(port.toInt()); if (!password.isEmpty()) server.setPassword(password); if (useSSL) server.setSSLEnabled(true); settings.setServer(server); if (!nick.isEmpty()) settings.setInitialNick(nick); if (!channel.isEmpty()) { Konversation::ChannelSettings channelSettings(channel); Konversation::ChannelList cl; cl << channelSettings; settings.setOneShotChannelList(cl); } } connectTo(flag, settings); }
MainWindow::MainWindow(QString filename, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowTitle(QApplication::applicationName()+" "+ QApplication::applicationVersion()); //ui->lastValuesBox->hide(); bytesRead=0; bytesWritten=0; lastValueDoubleClick=new DoubleClickEventFilter(this); ui->lastValuesBox->installEventFilter(lastValueDoubleClick); connect (lastValueDoubleClick,SIGNAL(doubleClicked()),this,SLOT(clearLastValues())); connect (lastValueDoubleClick,SIGNAL(doubleClicked()),this,SLOT(initLastValues())); appSettings=new QSettings(QSettings::IniFormat,QSettings::UserScope,QApplication::organizationName(),QApplication::applicationName(),this); data=new ExperimentData(this); dilatometerData=new DilatometerData(this); data->setDilatometerData(dilatometerData); experiment=new Experiment(&tcpClient,this); dilatometerPlot=NULL; plot=new Plot(this); plot->setExperimentData(data); plot->setAxisTitle(QwtPlot::xBottom,tr("t, sec")); ui->plotLayout->addWidget(plot); connect(ui->actionFullscreen,SIGNAL(triggered(bool)),this,SLOT(setFullscreen(bool))); connect(ui->actionExit,SIGNAL(triggered()),this,SLOT(close())); connect(ui->actionConnect_to,SIGNAL(triggered()),this,SLOT(connectTo())); connect(ui->actionDisconnect,SIGNAL(triggered()),this,SLOT(socketDisconnect())); connect(ui->actionViewData,SIGNAL(triggered()),this,SLOT(showDataViewWindow())); connect(ui->actionReplot,SIGNAL(triggered()),plot,SLOT(replot())); connect(ui->actionClear_plot,SIGNAL(triggered()),plot,SLOT(clear())); connect(ui->actionInitialize,SIGNAL(triggered()),plot,SLOT(initialize())); connect(ui->actionSelect_points,SIGNAL(toggled(bool)),plot,SLOT(selectPointsMode(bool))); connect(ui->actionZoom_to_extents,SIGNAL(triggered()),plot,SLOT(zoomExtents())); connect(ui->actionDraw_incremental,SIGNAL(triggered(bool)),plot,SLOT(setIncrementalDraw(bool))); connect(ui->actionOpen_file,SIGNAL(triggered()),SLOT(openFile())); connect(ui->actionSave_as,SIGNAL(triggered()),SLOT(saveFile())); connect(ui->actionMonitoring_interval,SIGNAL(triggered()),SLOT(setMonitoringInterval())); connect(ui->actionSetup,SIGNAL(triggered()),SLOT(showSetupCurvesDialog())); connect(ui->actionSet_interval,SIGNAL(triggered()),SLOT(setInterval())); connect(ui->actionControl,SIGNAL(triggered()),SLOT(viewExperimentControlDialog())); connect(ui->actionStart,SIGNAL(triggered(bool)),&tcpClient,SLOT(start(bool))); connect(ui->actionApproximate,SIGNAL(triggered()),SLOT(approximate())); connect(ui->actionShow_approximations,SIGNAL(triggered(bool)),plot,SLOT(showApproximationCurves(bool))); connect(ui->actionConfiguration,SIGNAL(triggered()),SLOT(showConfigurationDialog())); connect(ui->actionLast_calculation,SIGNAL(triggered()),SLOT(showCalculationLog())); connect(ui->actionDilatometry,SIGNAL(toggled(bool)),SLOT(showDilatometryPlot(bool))); connect(ui->actionZoom_yLeft_to_extents,SIGNAL(triggered()),SLOT(zoomYLeftToExtents())); connect(ui->actionAbout_Qt,SIGNAL(triggered()),QApplication::instance(),SLOT(aboutQt())); connect(ui->actionAbout,SIGNAL(triggered()),SLOT(showAbout())); connect(ui->actionSet_tolerance_alarm,SIGNAL(triggered()),plot,SLOT(setToleranceAlarm())); connect(ui->actionRemove_tolerance_alarm,SIGNAL(triggered()),plot,SLOT(removeToleranceAlarm())); connect(ui->actionView_tolerance,SIGNAL(triggered()),SLOT(showToleranceAlarmState())); plot->enableAutoZoom(ui->actionAuto_zoom->isChecked()); connect(ui->actionAuto_zoom,SIGNAL(triggered(bool)),plot,SLOT(enableAutoZoom(bool))); //ui->actionDraw_incremental->trigger(); connect(plot,SIGNAL(message(QString)),statusBar(),SLOT(showMessage(QString))); connect(ui->actionSelectT0,SIGNAL(toggled(bool)),plot,SLOT(selectT0(bool))); connect(plot,SIGNAL(T0Selected(bool)),ui->actionSelectT0,SLOT(trigger())); connect(plot,SIGNAL(T0Selected(bool)),ui->actionSelect_points,SLOT(setChecked(bool))); connect(plot,SIGNAL(toleranceAlarmSet(bool)),SLOT(toleranceAlarmStatusChange(bool))); connect(plot,SIGNAL(curvePointClicked(QwtPlotCurve*,int)),this,SLOT(updateSelectedValue(QwtPlotCurve*,int))); connect(&tcpClient,SIGNAL(connected()),this,SLOT(socketConnectedToServer())); connect(&tcpClient,SIGNAL(disconnected()),this,SLOT(socketDisconnectedFromServer())); connect(&tcpClient,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(socketStateChanged(QAbstractSocket::SocketState))); connect(&tcpClient,SIGNAL(dataLine(QByteArray&)),data,SLOT(parseLine(QByteArray&))); connect(&tcpClient,SIGNAL(initialData()),plot,SLOT(clear())); connect(&tcpClient,SIGNAL(initialData()),data,SLOT(resetData())); connect(&tcpClient,SIGNAL(serverStatus(bool)),ui->actionStart,SLOT(setChecked(bool))); connect(&tcpClient,SIGNAL(bytesWritten(int)),this,SLOT(appendBytesWritten(int))); connect(&tcpClient,SIGNAL(bytesRead(int)),this,SLOT(appendBytesRead(int))); connect(&tcpClient,SIGNAL(serverInterval(int)),experiment,SLOT(setInterval(int))); connect(data,SIGNAL(initialized()),plot,SLOT(initialize())); connect(data,SIGNAL(initialized()),this,SLOT(initLastValues())); connect(data,SIGNAL(pointCount(int)),&pointCountLabel,SLOT(setNum(int))); connect(data,SIGNAL(pointCount(int)),plot,SLOT(drawLastPoint())); /** This connection will cause to plot VLine markers*/ //connect(data,SIGNAL(marker(QPointF,int)),plot,SLOT(appendMarker(QPointF,int))); connect(data,SIGNAL(marker(int)),plot,SLOT(appendMarker(int))); connect(data,SIGNAL(pointCount(int)),this,SLOT(updateLastValues())); connect(data,SIGNAL(heaterPower(int)),this,SLOT(setHeaterPower(int))); connectionLabel.setText("*"); connectionLabel.setToolTip(tr("Connection status:\nGreen - connected\nRed - disconnected")); connectionLabel.setStyleSheet("QLabel {color:red; font-weight:bold;}"); pointCountLabel.setText("0"); pointCountLabel.setToolTip(tr("Number of points")); bytesWrittenLabel.setText("0"); bytesWrittenLabel.setToolTip("Bytes written to network"); bytesReadLabel.setText("0"); bytesReadLabel.setToolTip("Bytes read from network"); ui->heaterPowerBar->setStyleSheet("QProgressBar::chunk {margin: 0px; width: 1px;}"); ui->statusBar->addPermanentWidget(&bytesReadLabel); ui->statusBar->addPermanentWidget(&bytesWrittenLabel); ui->statusBar->addPermanentWidget(&pointCountLabel); ui->statusBar->addPermanentWidget(&connectionLabel); //if file was specified on startup - try open it if (!filename.isEmpty()) openFile(filename); }
void MjpegClient::reconnect() { log(QString("Attempting to reconnect to http://%1:%2%3").arg(m_host).arg(m_port).arg(m_url)); connectTo(m_host,m_port,m_url); }
sptr<HalfEdge> HalfEdge::connectTo(sPoint i_Pt) { return connectTo(sptr<HalfEdge>(new HalfEdge(i_Pt))); }
int main( int argc, char **argv ) { int sock, i; pid_t childPID; uint16_t port; ReadBuf *fromServer; fd_set readfds; char line[ READBUF_LEN ]; if( argc < ARG_MIN_ARGS ) { printUsage( stderr ); exit( EXIT_FAILURE ); } /* connect to the server */ if( sscanf( argv[ ARG_SERVERPORT ], "%"SCNu16, &port ) < 1 ) { fprintf( stderr, "ERROR: invalid port %s\n", argv[ ARG_SERVERPORT ] ); exit( EXIT_FAILURE ); } sock = connectTo( argv[ ARG_SERVERNAME ], port ); if( sock < 0 ) { exit( EXIT_FAILURE ); } // EJ additions 9/3/2012 // Turn on keep-alive for socket connection with more frequent checking // than the Linux default. What I've observed is that if a socket // connection is idle for long enough it gets dropped. This only // happens for some users. int on = 1; if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1) { fprintf( stderr, "ERROR: setsockopt failed; errno %i\n", errno ); exit( EXIT_FAILURE ); } // Not sure what this should be int num_before_failure = 2; if (setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &num_before_failure, sizeof(num_before_failure)) == -1) { fprintf( stderr, "ERROR: setsockopt failed; errno %i\n", errno ); exit( EXIT_FAILURE ); } // First check after 60 seconds int initial_secs = 60; if (setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &initial_secs, sizeof(initial_secs)) == -1) { fprintf( stderr, "ERROR: setsockopt failed; errno %i\n", errno ); exit( EXIT_FAILURE ); } // Thereafter, also check every 60 seconds int interval_secs = 60; if (setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &interval_secs, sizeof(interval_secs)) == -1) { fprintf( stderr, "ERROR: setsockopt failed; errno %i\n", errno ); exit( EXIT_FAILURE ); } /* set up read buffers */ fromServer = createReadBuf( sock ); /* write to server */ line[0] = 0; for( i = 3; i < argc; ++i ) { strcat( line, argv[i] ); if ( i < argc - 1 ) { strcat( line, " " ); } } strcat( line, "\n" ); int len = strlen(line); if( write( sock, line, len ) < 0 ) { fprintf( stderr, "ERROR: failed while sending to server\n" ); exit( EXIT_FAILURE ); } /* main loop */ while( 1 ) { /* clean up any children */ while( waitpid( -1, NULL, WNOHANG ) > 0 ); /* wait for input */ FD_ZERO( &readfds ); FD_SET( sock, &readfds ); i = select( sock + 1, &readfds, NULL, NULL, NULL ); if( i < 0 ) { fprintf( stderr, "ERROR: select failed\n" ); exit( EXIT_FAILURE ); } if( i == 0 ) { /* nothing ready - shouldn't happen without timeout */ continue; } /* handle server messages */ if( FD_ISSET( sock, &readfds ) ) { /* get the input */ while( ( i = getLine( fromServer, READBUF_LEN, line, 0 ) ) >= 0 ) { if( i == 0 ) { /* This could be an error or could just signify successful completion of all matches */ fprintf( stderr, "Server closed connection\n" ); exit( EXIT_SUCCESS ); } /* check for server commands */ if( strncasecmp( line, "run ", 4 ) == 0 ) { /* split the rest of the line into name ' ' port */ for( i = 4; line[ i ]; ++i ) { if( line[ i ] == ' ' ) { /* found the separator */ line[ i ] = 0; break; } } printf( "starting match %s:%s", &line[ 4 ], &line[ i + 1 ] ); fflush( stdout ); /* run `command machine port` */ childPID = fork(); if( childPID < 0 ) { fprintf( stderr, "ERROR: fork() failed\n" ); exit( EXIT_FAILURE ); } if( childPID == 0 ) { /* child runs the command */ execl( argv[ ARG_BOT_COMMAND ], argv[ ARG_BOT_COMMAND ], &line[ 4 ], &line[ i + 1 ], NULL ); fprintf( stderr, "ERROR: could not run %s\n", argv[ ARG_BOT_COMMAND ] ); exit( EXIT_FAILURE ); } } else { /* just a message, print it out */ if( fwrite( line, 1, i, stdout ) < 0 ) { fprintf( stderr, "ERROR: failed while printing server message\n" ); exit( EXIT_FAILURE ); } fflush( stdout ); if( ! strcmp( line, "Matches finished\n") ) { exit( EXIT_SUCCESS ); } } } } } return EXIT_SUCCESS; }
/* Implementation of LocalSyscallProxy */ LocalSyscallProxy::LocalSyscallProxy(RayCanvas *canvas, QObject *mainProxy) : m_canvas(canvas) { if (mainProxy) // auto-connect to mainProxy connectTo(mainProxy); }
bool TcpMq::connectTo(const string& serverName, unsigned int serverPort, int zmqClientSocketType) { return connectTo(serverName, boost::lexical_cast<std::string>(serverPort), zmqClientSocketType); }