OlsrEventServer::OlsrEventServer(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { //std::cout << "OLSR event server listening on port " << port << std::endl; SER_PRINTF("OLSR event server listening on port %d",port); waitForConnection(); }
void ServerConnection::onTunnelCreate(const std::function<void(Tunnel*)> &onTunnel, const std::string &key) { waitForConnection(); json v; v["id"] = "session/enable"; v["data"].push_back("tunnel"); if(key != "") v["key"] = key; send(v); tunnelCallback = onTunnel; }
int main (int argc, char *argv[]) { printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving bmps since 2012\n"); int serverSocket = makeServerSocket (DEFAULT_PORT); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection (serverSocket); // wait for a request to be sent from a web browser, open a new // connection for this conversation // read the first line of the request sent by the browser int bytesRead; bytesRead = read (connectionSocket, request, (sizeof request)-1); assert (bytesRead >= 0); // were we able to read any data from the connection? // print entire request to the console printf (" *** Received http request ***\n %s\n", request); //send the browser a simple html page using http printf (" *** Sending http response ***\n"); serveBMP(connectionSocket); short URLCoor = sscanf(request, "%*s /X%lf_Y%lf_Z%lfd.bmp", &xurl, &yurl, &zurl); if (URLCoor == 3){ serveBMP(connectionSocket); } else{ serveHTML(connectionSocket);} // close the connection after sending the page- keep aust beautiful close(connectionSocket); numberServed++; } // close the server connection after we are done- keep aust beautiful printf ("** shutting down the server **\n"); close (serverSocket); return EXIT_SUCCESS; }
int main (int argc, char* argv[]) { #ifdef _WIN32 WSADATA wsaData; WSAStartup((2 << 8) + 2, &wsaData); #endif puts("************************************"); printf("Starting simple server %f\n", SIMPLE_SERVER_VERSION); puts("Serving poetry since 2011"); int serverSocket = makeServerSocket(DEFAULT_PORT); printf("Access this server at http://localhost:%d/\n", DEFAULT_PORT); puts("************************************"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while ( numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection(serverSocket); // wait for a request to be sent from a web browser, open a new // connection for this conversation // read the first line of the request sent by the browser int bytesRead = recv (connectionSocket, request, sizeof(request) - 1, 0); assert (bytesRead >= 0); // were we able to read any data from the connection? // print entire request to the console printf (" *** Received http request ***\n %s\n", request); //send the browser a simple html page using http puts (" *** Sending http response ***"); serveHTML (connectionSocket); // close the connection after sending the page- keep aust beautiful close (connectionSocket); ++numberServed; } // close the server connection after we are done- keep aust beautiful puts("** shutting down the server **"); close (serverSocket); #ifdef _WIN32 WSACleanup(); #endif return EXIT_SUCCESS; }
static void chanSwitchAccept(TChanSwitch * const chanSwitchP, TChannel ** const channelPP, void ** const channelInfoPP, const char ** const errorP) { /*---------------------------------------------------------------------------- Accept a connection via the channel switch *chanSwitchP. Return as *channelPP the channel for the accepted connection. If no connection is waiting at *chanSwitchP, wait until one is. If we receive a signal while waiting, return immediately with *channelPP == NULL. -----------------------------------------------------------------------------*/ struct socketUnix * const listenSocketP = chanSwitchP->implP; bool interrupted; TChannel * channelP; interrupted = FALSE; /* Haven't been interrupted yet */ channelP = NULL; /* No connection yet */ *errorP = NULL; /* No error yet */ while (!channelP && !*errorP && !interrupted) { waitForConnection(listenSocketP, &interrupted, errorP); if (!*errorP && !interrupted) { struct sockaddr peerAddr; socklen_t size = sizeof(peerAddr); int rc; rc = accept(listenSocketP->fd, &peerAddr, &size); if (rc >= 0) { int const acceptedFd = rc; createChannelForAccept(acceptedFd, peerAddr, &channelP, channelInfoPP, errorP); if (*errorP) close(acceptedFd); } else if (errno == EINTR) interrupted = TRUE; else xmlrpc_asprintf(errorP, "accept() failed, errno = %d (%s)", errno, strerror(errno)); } } *channelPP = channelP; }
/** A file is sent by the host * * \param filename The filename to create * */ void RainbruRPG::Network::Ftp::FtpTransfer:: commandSTOR(const QString& filename){ LOGI("Executing STOR command"); nextCommand=FTC_STOR; std::string strFilename(filename.toLatin1()); GlobalURI gu; std::string strNnextFilename=gu.getQuarantineFile(strFilename); nextFilename=strNnextFilename.c_str(); nextOnlyFilename=filename; QTcpSocket* sock; waitForConnection(sock); }
ConnectionManager::ConnectionManager( boost::asio::io_service& boostReactor, const boost::asio::ip::tcp::endpoint& endpoint ) : boostReactor( boostReactor ), connectionAcceptor( boostReactor, endpoint ), connections(), consumerByGame(), providerByGame(), gameDefinitions(), games() { // waiting for the connection waitForConnection(); }
void OlsrEventServer::handleAccept(TcpConnectionPtr connectionPtr, const boost::system::error_code& error) { if (!error) { SER_PRINTF("Got new connection"); EventListenerPtr newListener(new EventListener(connectionPtr, eventListenerManager_)); newListener->start(); dev_send_init(); tc_send_all_data(); dev_send(); // Waiting for new connection again waitForConnection(); } }
int main (int argc, char *argv[]) { testPositivePower(); printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving bmps since 2012\n"); int serverSocket = makeServerSocket (DEFAULT_PORT); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection (serverSocket); int bytesRead; bytesRead = read (connectionSocket, request, (sizeof request)-1); assert (bytesRead >= 0); printf (" *** Received http request ***\n %s\n", request); printf (" *** Sending http response ***\n"); printf("%s\n", request); if (strstr(request, "bmp") != NULL) { serveBMP(connectionSocket, request); } else { serveHTML(connectionSocket); } close(connectionSocket); numberServed++; } printf ("** shutting down the server **\n"); close (serverSocket); return EXIT_SUCCESS; }
int main (int argc, char* argv[]) { printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving poetry since 2011\n"); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); int serverSocket = makeServerSocket(DEFAULT_PORT); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); // STEP 1. wait for a request to be sent from a web browser, // then open a new connection for this conversation int connectionSocket = waitForConnection(serverSocket); // STEP 2. read the first line of the request int bytesRead = recv (connectionSocket, request, sizeof(request) - 1, 0); assert (bytesRead >= 0); // check that we were able to read some data from the connection // echo entire request to the console for debugging printf (" *** Received http request ***\n %s\n", request); // STEP 3. send the browser a simple html page using http printf (" *** Sending http response ***\n"); serveHTML (connectionSocket); // STEP 4. close the connection after sending the page- keep aust beautiful close (connectionSocket); ++numberServed; } // close the server connection after we are done- keep aust beautiful printf ("** shutting down the server **\n"); #if PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX close( serverSocket); #elif PLATFORM == PLATFORM_WINDOWS closesocket( serverSocket ); WSACleanup(); #endif return EXIT_SUCCESS; }
Tunnel* ServerConnection::createTunnel(const std::string &sessionId) { waitForConnection(); json data; data["session"] = sessionId; json result = call("tunnel/create", data); if (result["status"] == "ok") { Tunnel* t = new Tunnel(result["id"], this); tunnels[t->id] = t; return t; } logger<<"Could not create tunnel!\n"<< result << Log::newline; return NULL; }
int main(int argc, char * argv[]) { char * serverPort = DEFAULT_PORT; int ch; while((ch = getopt(argc, argv, "p:h")) != -1) { switch(ch) { // Set the server port. If not given, DEFAULT_PORT is used. case 'p': serverPort = optarg; break; case 'h': default: usage(); } } int sd = openSocket(NULL, serverPort, SERVER); if (!sd) { fprintf(stderr, "Unable to create server socket.\n"); exit(EXIT_FAILURE); } printf("Waiting for connections...\n"); // Wait for a client to connect then pass off the socket descriptor to a // new thread to deal with it. Go back to wait for another client. while (1 == 1) { // TODO: Catch cntr-c. Then we can set a flag and check for it in // this loop. Maybe accept stdin as well? // If the user wants to exit, if no clients connected, let them exit. // Otherwise ask if they are sure. pthread_t tid; int cd = waitForConnection(sd); if (cd == -1) { fprintf(stderr, "Could not accept client connection.\n"); continue; } pthread_create(&tid, NULL, handleConnection, &cd); } close(sd); }
int main(int argc, char* argv[]) { Kontroller kontroller; if (!waitForConnection(kontroller)) { return 0; } kontroller.enableLEDControl(true); PongGame game(3.0f); std::array<std::array<bool, kScreenHeight>, kScreenWidth> pixels = {}; std::chrono::high_resolution_clock::time_point lastTime = std::chrono::high_resolution_clock::now(); bool quit = false; while (!quit && kontroller.isConnected()) { std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now(); double dt = std::chrono::duration_cast<std::chrono::duration<double>>(now - lastTime).count(); lastTime = now; kontroller.poll(); const Kontroller::State& state = kontroller.getState(); quit = state.stop; float leftPaddlePos = state.columns[0].slider; float rightPaddlePos = state.columns[7].slider; game.tick(static_cast<float>(dt), leftPaddlePos, rightPaddlePos); game.draw(pixels); draw(kontroller, pixels); std::this_thread::sleep_for(std::chrono::milliseconds(16)); } // Clear the LEDs if (kontroller.isConnected()) { pixels = {}; draw(kontroller, pixels); kontroller.enableLEDControl(false); } return 0; }
void ConnectionManager::handle_accept( const boost::system::error_code& error, connection_ptr new_connection ) { if ( error == 0) { // create the unique id std::string newClientName = createNewClientName(); AsyncLogger::getInstance()->log( "ConnectionManager> Connection accepted> " + newClientName ); // create the client ClientConnectionPtr client = ClientConnection::create( newClientName, this, new_connection ); // and back to client acceptance waitForConnection(); } else { std::cerr << "ConnectionManager> " << "Connection refused" << std::endl; } }
void RRPlugin::postSwapBuffers(int windowNumber) { if (windowNumber != 0) return; if (!coVRMSController::instance()->isMaster()) return; if (!m_rrdpy) { if (m_clientList.empty()) waitForConnection(); else tryConnect(true); } if (!m_rrdpy) return; try { sendvgl(m_rrdpy, GL_FRONT, false, fconfig.compress, fconfig.qual, fconfig.subsamp, true /*block*/); while (rrxevent *rev = m_rrdpy->getevent()) { m_eventQueue.push_back(*rev); delete rev; } } catch (...) { delete m_rrdpy; m_rrdpy = NULL; fprintf(stderr, "sendvgl failed\n"); } }
int ELFIN::CConnectionFnCMgr::startConnection(ProgramOptions *_progOpt) { LLRP::CTypeRegistry * pTypeRegistry; int rc; /* * Allocate the type registry. This is needed * by the connection to decode. */ pTypeRegistry = LLRP::getTheTypeRegistry(); if(NULL == pTypeRegistry) { READER_LOG(LOGTYPE_ERROR, "getTheTypeRegistry failed\n"); //return -1; } //Enrollment of LLRP 1.1 Extension to the type registry //enrollLLRP1x1ExtTypesIntoRegistry(pTypeRegistry); _pTypeRegistry = pTypeRegistry; /* * Construct a connection (LLRP::CConnection). * Using a 32kb max frame size for send/recv. * The connection object is ready for business * but not actually connected to the reader yet. */ if (_pConn != NULL) { READER_LOG(LOGTYPE_ERROR, "_pConn is not NULL\n"); } _portNum = _progOpt->getFnCPort(); _pConn = new CConnectionFnC(pTypeRegistry, CCONNECTION_BUFFER_SIZE, _portNum); if(NULL == _pConn) { READER_LOG(LOGTYPE_ERROR, "new CConnection failed\n"); rc = -2; //return -2; } _isReaderInitiated = _progOpt->getReaderInitiatedOpt(); if (_isReaderInitiated == 1) { std::string FnCHostName = _progOpt->getFnCAddress(); READER_LOG(LOGTYPE_INFO, "LLRP Reader starts in client mode....\n"); rc = openConnectionToFnC(FnCHostName.c_str()); } else if (_isReaderInitiated == -1) { exit(0); } else { READER_LOG(LOGTYPE_INFO, "LLRP Reader starts in server mode....\n"); READER_LOG(LOGTYPE_INFO, "Start waiting connection....\n"); rc = waitForConnection(); } if (rc == 0) { READER_LOG(LOGTYPE_INFO, "Connected, checking status....\n"); _isConnected = 1; sendConnectionAttemptEvent(); } else { READER_LOG(LOGTYPE_INFO, "Connection failed\n"); delete _pTypeRegistry; _pTypeRegistry = NULL; delete _pConn; _pConn = NULL; _isConnected = 0; } return rc; }
void startServer(int port) { // Make sure types have the required size. assert(sizeof(bits8) == 1); assert(sizeof(bits16) == 2); assert(sizeof(bits32) == 4); int parsedValues; #ifdef _WIN32 WSADATA wsaData; WSAStartup(0x0202, &wsaData); #endif int sock = makeSocket(port); char req[REQ_SIZE + 1]; req[REQ_SIZE] = 0; while (1) { int conn = waitForConnection(sock); recv(conn, req, REQ_SIZE, 0); // Cut the string off to one line. char *endOfLine = strchr(req, '\n'); if (endOfLine != NULL) { *endOfLine = '\0'; } // Find the path. char path[PATH_SIZE + 1]; parsedValues = sscanf(req, "GET %s HTTP/1.1", path); if (parsedValues == 1) { if (strcmp(path, "/") == 0) { // Homepage char *msg = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html\r\n" "\r\n" "<!DOCTYPE html>\n" "<script src=\"http://almondbread.cse.unsw.edu.au/tiles.js\"></script>\n"; send(conn, msg, strlen(msg), 0); } else { double x, y; int zoom; parsedValues = sscanf( path, "/tile_x%lf_y%lf_z%d.bmp", &x, &y, &zoom); if (parsedValues == 3) { char *msg = "HTTP/1.0 200 OK\r\n" "Content-Type: image/bmp\r\n" "\r\n"; send(conn, msg, strlen(msg), 0); char image[FILE_SIZE]; mandelBitmap(image, x, y, zoom); send(conn, image, FILE_SIZE, 0); } else { // HTTP Error 404. } } } else { // HTTP Error 400. } closeSocket(conn); } // Closing the socket is unnecessary, because the OS will // immediately recover it thanks to SO_REUSEADDR. }
int main(int argc, char *argv[], char *envp[]) { int in[2], out[2], err[2]; int status; int ssh_stdinfd, ssh_stdoutfd, ssh_stderrfd; if (argc < 2) { printf("***ERROR: This program shouldn't be used directly.\n"); exit(1); } if (strcmp(argv[1], "--noStrictHostKeyChecking") == 0) { noStrictHostKeyChecking = 1; argv++; } createStdioFds(in, out, err); listenSock = openListenSocket(); signal(SIGCHLD, signal_handler); pid_t sshChildPid = fork(); if (sshChildPid == 0) { char buf[PATH_MAX + 80]; char hostname[80]; int port = getport(listenSock); close(listenSock); close(in[1]); close(out[0]); close(err[0]); dup2(in[0], STDIN_FILENO); dup2(out[1], STDOUT_FILENO); dup2(err[1], STDERR_FILENO); unsetenv("LD_PRELOAD"); // Replace dmtcp_sshd replace with "dmtcp_sshd --host <host> --port <port>" struct in_addr saddr; if (dmtcp_get_local_ip_addr == NULL) { printf("ERROR: Unable to find dmtcp_get_local_ip_addr.\n"); abort(); } dmtcp_get_local_ip_addr(&saddr); char *hostip = inet_ntoa(saddr); strcpy(hostname, hostip); size_t i = 0; while (argv[i] != NULL) { // "dmtcp_sshd" may be embedded deep inside the command line. char *ptr = strstr(argv[i], SSHD_BINARY); if (ptr != NULL) { ptr += strlen(SSHD_BINARY); if (*ptr != '\0') { *ptr = '\0'; ptr++; } snprintf(buf, sizeof buf, "%s --host %s --port %d %s", argv[i], hostip, port, ptr); argv[i] = buf; } i++; } execvp(argv[1], &argv[1]); printf("%s:%d DMTCP Error detected. Failed to exec.", __FILE__, __LINE__); abort(); } int childSock = waitForConnection(listenSock); close(in[0]); close(out[1]); close(err[1]); ssh_stdinfd = in[1]; ssh_stdoutfd = out[0]; ssh_stderrfd = err[0]; assert(dmtcp_ssh_register_fds != NULL); dmtcp_ssh_register_fds(false, ssh_stdinfd, ssh_stdoutfd, ssh_stderrfd, childSock, noStrictHostKeyChecking); client_loop(ssh_stdinfd, ssh_stdoutfd, ssh_stderrfd, childSock); wait(&status); return status; }
//Begins the connection void establishConnection(char *type, int *replay, char *ip) { //Ensure players cannot leave signal(SIGINT, leaveError); //Server variables struct sockaddr_in dataAddr; int clientSocket; struct sockaddr_in myAddr; int i, addrSize; char buffer[50]; //Game variables char o_phrase[40]; char my_phrase[40]; char h_o_phrase[40]; char h_my_phrase[40]; char board[1000]; board[0] = '\0'; char guess[80]; guess[0] = '\0'; int bytesRcv; int win = 0; //Server connect if (strcmp(type, "server") == 0) { setupSocket(&myListenSocket, &myAddr, type, ""); bindSocket(&myListenSocket, &myAddr); waitForConnection(&myListenSocket, &myAddr, &clientSocket, &dataAddr); //fix } //Client connect if (strcmp(type, "client") == 0) { setupSocket(&clientSocket, &dataAddr, type, ip); connectAsClient(&clientSocket, &dataAddr); } //Loop while the game is supposed to be played again while (*replay == 1) { //Creates the player's phrase, hides it and stores the unhidden phrase in the buffer game_createPhrase(my_phrase); game_toHidden(my_phrase, h_my_phrase); strcpy(buffer, my_phrase); //Send the phrase to the other player and wait for them to send back send(clientSocket, buffer, strlen(buffer), 0); fprintf(stdout, "Waiting for your opponent to create their secret phrase...\n"); //Store what was sent back in the opponent's phrase variable bytesRcv = recv(clientSocket, buffer, sizeof(buffer), 0); buffer[bytesRcv] = '\0'; strcpy(o_phrase, buffer); //Hide their phrase and create the board to print on screen game_toHidden(o_phrase, h_o_phrase); game_makeBoard(h_my_phrase, h_o_phrase, board); //Show the player their own phrase fprintf(stdout, "Your phrase: %s\n\n", my_phrase); //Counter to make the client go first initially i = 0; //Game loop while (1) { //Ensures that the client goes first if (i > 0 || strcmp(type, "server") == 0) { //Wait for opponent to guess and store guess in buffer fprintf(stdout, "Waiting for your opponent's guess...\n"); bytesRcv = recv(clientSocket, buffer, sizeof(buffer), 0); buffer[bytesRcv] = '\0'; strcpy(guess, buffer); //Compare guess with the actual phrase and check for win condition (1 = win, 0 = no win) game_guess(guess, my_phrase, h_my_phrase, &win); if (win == 1) { win = 0; //Wait to see if the opponent wants to play again fprintf(stdout, "Your opponent has won. Please wait while he decides he wants to play again...\n"); bytesRcv = recv(clientSocket, buffer, sizeof(buffer), 0); buffer[bytesRcv] = '\0'; //If opponent sends back "left", we need to do some things depending on if the opponent was the host or not if (strcmp(buffer, "left") == 0) { fprintf(stdout, "Your opponent left!\n"); //If you were the server and lost if (strcmp(type, "server") == 0) { //Re-setup the socket and listen for a new connection setupSocket(&clientSocket, &myAddr, type, ""); waitForConnection(&myListenSocket, &myAddr, &clientSocket, &dataAddr); i = 0; break; } //Close the client socket, change player type to server and listen for a new connection else { close(clientSocket); strcpy(type, "server"); setupSocket(&myListenSocket, &dataAddr, type, ""); waitForConnection(&clientSocket, &dataAddr, &myListenSocket, &myAddr); //TODO fix break; } *replay = -1; return; } //If they didn't send back "left", then they want to play again //So simply break out of the game loop to start a new game with new phrases else { system("clear"); fprintf(stdout, "Your opponent wants to play again, let's go!\n"); break; } } //Update the game board game_makeBoard(h_my_phrase, h_o_phrase, board); fprintf(stdout, "Your phrase: %s\n\n", my_phrase); fprintf(stdout, "Your opponent guessed: %s\n", guess); } //Ask for user input fprintf(stdout, "Guess a letter or the entire phrase.\n"); fgets(guess, sizeof(guess), stdin); guess[strlen(guess)-1] = '\0'; //Compare guess with the actual phrase and check for win condition (1 = win, 0 = no win), then update the game baord game_guess(guess, o_phrase, h_o_phrase, &win); game_makeBoard(h_my_phrase, h_o_phrase, board); fprintf(stdout, "Your phrase: %s\n\n", my_phrase); //Send the opponent what the user guessed strcpy(buffer, guess); send(clientSocket, buffer, strlen(buffer), 0); //If the user won, then see if they want to play again if (win == 1) { game_playAgain(replay); //Wants to play again if (*replay == 1) { strcpy(buffer, "stay"); send(clientSocket, buffer, strlen(buffer), 0); win = 0; break; } //Doesn't want to play again else { strcpy(buffer, "left"); send(clientSocket, buffer, strlen(buffer), 0); //Reset SIGINT to its default functionality signal(SIGINT, SIG_DFL); return; } } //Increment i allowing for the server to have a guess i++; } } //Close the final listen socket (never occurs) close(myListenSocket); }
int doSession(int listenSocket) { int serverSocket = INVALID_SOCKET; // Connection to the server (gdbserver) int clientSocket = INVALID_SOCKET; // Connection to the client (GDB) int rc = GDB_OK; // Wait for connection from GDB do { rc = waitForConnection(listenSocket, &clientSocket); } while (rc == GDB_NON_FATAL_ERROR); if (rc == GDB_FATAL_ERROR) { return GDB_FATAL_ERROR; } // Connect to gdbserver if (createSocket(&serverSocket, -1, FALSE) != GDB_OK) { return GDB_FATAL_ERROR; } if (connectToServer(serverSocket) != GDB_OK) { return GDB_FATAL_ERROR; } // Transfer data (GDB Session) do { struct timeval sendTime; gettimeofday(&sendTime, NULL); char buffer[4000]; int size = 0; int activeSocket = waitForActivity(clientSocket, serverSocket); if (activeSocket == clientSocket) { gettimeofday(&sendTime, NULL); size = getData(TRUE, 0, clientSocket, buffer, sizeof(buffer)); if (size > 0) { sendData(serverSocket, buffer, size); } else if (size == -GDB_FATAL_ERROR) { rc = GDB_FATAL_ERROR; } } else if (activeSocket == serverSocket) { struct timeval currentTime; gettimeofday(¤tTime, NULL); double elapsedTime = timeval_subtract(¤tTime, &sendTime); size = getData(FALSE, elapsedTime, serverSocket, buffer, sizeof(buffer)); if (size > 0) { sendData(clientSocket, buffer, size); } else if (size == -GDB_FATAL_ERROR) { rc = GDB_FATAL_ERROR; } } else if (activeSocket == -GDB_FATAL_ERROR) { rc = GDB_FATAL_ERROR; } } while ((rc != GDB_FATAL_ERROR)); if (clientSocket >= 0) { closesocket(clientSocket); } if (serverSocket >= 0) { closesocket(serverSocket); } return GDB_NON_FATAL_ERROR; }
int main (int argc, char *argv[]) { // Test URL extraction function. testGetRequest(); printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving the Mandelbrot since 2011\n"); int serverSocket = makeServerSocket (DEFAULT_PORT); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection (serverSocket); // Wait for a request to be sent from a web browser, open a new // Connection for this conversation // Read the first line of the request sent by the browser int bytesRead; bytesRead = read (connectionSocket, request, (sizeof request)-1); assert (bytesRead >= 0); // Were we able to read any data from the connection? //determine if there is an X in the request if(isXFound(request)){ // Read x,y,zoom from URL. getRequest(request); // Print entire request to the console printf (" *** Received http request ***\n %s\n", request); // Send the browser a simple html page using http printf (" *** Sending http response ***\n"); serveHTML(connectionSocket); } else { // Print entire request to the console printf (" *** Received http request ***\n %s\n", request); // Send the browser a simple html page using http printf (" *** Sending http response ***\n"); serveInteractiveJS(connectionSocket); } // Close the connection after sending the page- keep aust beautiful close(connectionSocket); numberServed++; } // close the server connection after we are done- keep aust beautiful printf ("** shutting down the server **\n"); close (serverSocket); return EXIT_SUCCESS; }
/** A file is requested by the host * * This function is called when the client retirieve a file. The file * is sent to the client from the \c uploaded directory. * * \param filename The filename without path * */ void RainbruRPG::Network::Ftp::FtpTransfer:: commandRETR(const QString& filename){ LOGI("Sending file..."); QString s("Sending file "); s+=filename; emit(log(s)); LOGI(s.toLatin1()); nextCommand=FTC_RETR; // Get the absolute filename GlobalURI gu; std::string stdFilename(filename.toLatin1()); std::string fullFileName=gu.getUploadFile(stdFilename); nextFilename=filename; nextOnlyFilename=filename; LOGCATS("Opening file '"); LOGCATS(fullFileName.c_str()); LOGCAT(); QFile f(fullFileName.c_str()); QIODevice::OpenMode om; // We are in Binary mode if (transferType==FTT_BINARY){ om=QIODevice::ReadOnly; } // We are in ASCII mode else if (transferType==FTT_ASCII){ om=QIODevice::ReadOnly|QIODevice::Text; } if(f.open(om)){ QTcpSocket sock; if (waitForConnection(&sock)){ emit(startTransferFile(filename, f.size())); int rep=0; while (!f.atEnd()){ rep=sock.write(f.read(MAX_READ_LENGTH)); if (rep==-1){ LOGE("An error occured during RETR command"); break; } else{ LOGCATS("Writing "); LOGCATI(rep); LOGCATS(" bytes"); LOGCAT(); sock.waitForBytesWritten(3000); } } // Transfer complete emit(log("Transfer channel closed")); emit(transferComplete(filename)); sock.disconnectFromHost(); LOGI("Transfer complete"); f.close(); } } else{ emit(log("An error occured during opening file :")); QFile::FileError fe=f.error(); QString feText; if (fe==QFile::OpenError){ feText=("5 The file could not be opened."); } else{ feText.setNum(fe); } emit(log(feText)); } }
int main (int argc, char *argv[]) { printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving bmps since 2012\n"); int serverSocket = makeServerSocket (DEFAULT_PORT); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection (serverSocket); // wait for a request to be sent from a web browser, open a new // connection for this conversation // read the first line of the request sent by the browser int bytesRead; bytesRead = read (connectionSocket, request, (sizeof request)-1); assert (bytesRead >= 0); // were we able to read any data from the connection? // print entire request to the console printf (" *** Received http request ***\n %s\n", request); //send the browser a simple html page using http double x = 0, y = 0; int levels, z; //========================================================================== //========================================================================== //========================================================================== levels = sscanf (request, "GET /tile_x%lf_y%lf_z%d.bmp", &x, &y, &z); printf("The levels of zoom: %d\n", z); printf("x value is %lf, y value is %lf\n", x, y); printf("===========================================\n"); //========================================================================== //========================================================================== //========================================================================== serveBMP(connectionSocket); // close the connection after sending the page- keep aust beautiful close(connectionSocket); numberServed++; } // close the server connection after we are done- keep aust beautiful printf ("** shutting down the server **\n"); close (serverSocket); return EXIT_SUCCESS; }
void GfxCountryMapGenerator::run() { const int maxHandshake = 1024; char handshake[maxHandshake]; TCPSocket* socket = waitForConnection(handshake, maxHandshake); if ( socket == NULL ) { mc2log << error << "No connection for GfxCountryMapGenerator" << endl; return; } DEBUG2(uint32 startTime = TimeUtility::getCurrentTime()); // We've got an request for a map... mc2dbg4 << "GfxCountryMapGenerator, sending map with ID " << mapIDs[0] << endl; CountryOverviewMap* theMap = dynamic_cast<CountryOverviewMap*>(mapHandler->getMap(mapIDs[0])); DEBUG8(cerr << "MAPID " << mapIDs[0] << endl); // Check if the map is valid or not if (theMap != NULL) { // OK, map valid! uint32 nbrMaps = theMap->getNbrMaps(); const GfxData* mapGfx = theMap->getGfxData(); // Calculate the size of the filtered map when written to a buffer. uint32 filtMapsBufSize = 0; const uint32 nbrFiltLevels = CountryOverviewMap::NBR_SIMPLIFIED_COUNTRY_GFX; for (uint32 i = 0; i < nbrFiltLevels; i++ ) { for (uint32 j = 0; j < mapGfx->getNbrPolygons(); j++ ) { const Stack* filtStack = theMap->getFilterStack(i,j); filtMapsBufSize += 4; // writes number of filt stack elements. for (uint32 k = 0; k < filtStack->getStackSize(); k++) { filtMapsBufSize += 4; // writes filt stack element. } } } // Claculate size of buffer needed. uint32 bufSize = 4; // nbrMaps bufSize += nbrMaps * 24; // nbrMaps * (mapId, creationTime, Bbox) bufSize += 4; // polygons closed, nbrPolygons bufSize += mapGfx->getNbrPolygons() * 4; // nbr coordinates per polygon. bufSize += theMap->getGfxData()->getTotalNbrCoordinates() * 8; // coords. bufSize += 4; // nbrFiltLevels bufSize += filtMapsBufSize; // Size of the filter data. DataBuffer idsAndGfx(bufSize); // Note that we multiply the size of the coordinates with two in // order to make space for the filtered versions of the country // GfxData as well. // DataBuffer idsAndGfx(nbrMaps * 24 + // ID + ver + Bbox // theMap->getGfxData()->getTotalNbrCoordinates()*8*2 + // 102400); // approx gfxdata idsAndGfx.writeNextLong(nbrMaps); for (uint32 i=0; i<nbrMaps; i++) { uint32 creationTime; int32 maxLat, minLat, maxLon, minLon; uint32 mapID = theMap->getMapData(i, creationTime, maxLat, minLon, minLat, maxLon); idsAndGfx.writeNextLong(mapID); idsAndGfx.writeNextLong(creationTime); idsAndGfx.writeNextLong(maxLat); idsAndGfx.writeNextLong(minLon); idsAndGfx.writeNextLong(minLat); idsAndGfx.writeNextLong(maxLon); mc2dbg1 << " Wrote mapID=" << mapID << ", version=" << creationTime << ", bbox=" << maxLat << ", " << minLon << ", " << minLat << ", " << maxLon << endl; } // Save the GfxData of the country //uint32 nbrPolygons = MIN(5, mapGfx->getNbrPolygons()); uint32 nbrPolygons = 0; // The polygons being sorted on nbrCoordinates, we an accept // to skip(send) 5 small polys with many coords, in order to // send larger polygons with fewer coordinates. uint32 maxNbrSkipPolys = 5; uint32 skipPolys[maxNbrSkipPolys]; for (uint32 i = 0; i < maxNbrSkipPolys;i++) { skipPolys[i] = MAX_UINT32; } bool cont = true; uint32 nbrSkip = 0; while (cont && (nbrPolygons < mapGfx->getNbrPolygons())) { mc2dbg8 << "poly " << nbrPolygons << " nbrC=" << mapGfx->getNbrCoordinates(nbrPolygons) << " length=" << mapGfx->getLength(nbrPolygons); if (mapGfx->getLength(nbrPolygons) < 35000) { skipPolys[nbrSkip] = nbrPolygons; mc2dbg8 << " - \"skipping\" "; nbrSkip++; if (nbrSkip >= maxNbrSkipPolys) { cont = false; } } mc2dbg8 << endl; nbrPolygons++; } // Don't send if any of the small polygons are the last ones.. uint32 p = maxNbrSkipPolys; while ( (p > 0) && (skipPolys[p-1] >= nbrPolygons-1)) { if (skipPolys[p-1] == nbrPolygons-1) { mc2dbg8 << " skip poly in the end of nbrPolygons" << endl; nbrPolygons--; } p--; } nbrPolygons=MAX(1, nbrPolygons); mc2dbg << "Sending " << nbrPolygons << " polygons of " << mapGfx->getNbrPolygons() << endl; idsAndGfx.writeNextBool(true); // polygons closed idsAndGfx.writeNextByte(0); // PAD idsAndGfx.writeNextShort(nbrPolygons);// # polygons for (uint32 p=0; p<nbrPolygons;p++) { uint32 nbrCoordinates = mapGfx->getNbrCoordinates(p); idsAndGfx.writeNextLong(nbrCoordinates); for (uint32 i = 0; i < nbrCoordinates; i++) { idsAndGfx.writeNextLong(mapGfx->getLat(p, i)); idsAndGfx.writeNextLong(mapGfx->getLon(p, i)); } } // Send filtered gfxdata information. // Nbr filtering levels idsAndGfx.writeNextLong(nbrFiltLevels); for (uint32 i = 0; i < nbrFiltLevels; i++ ) { // Nbr polygons already written before for (uint32 j = 0; j < nbrPolygons; j++ ) { const Stack* filtStack = theMap->getFilterStack(i,j); // Nbr indices in the filtering stack. idsAndGfx.writeNextLong(filtStack->getStackSize()); for (uint32 k = 0; k < filtStack->getStackSize(); k++) { // Index idsAndGfx.writeNextLong(filtStack->getElementAt(k)); } } } // Create and fill a buffer with the string items in this country DataBuffer stringItems(theMap->getMaximunSizeOfStringItems()*2 + 40000000); // length of items if (!theMap->saveStringItems(&stringItems)) { mc2log << error <<"Error saving string items for country" << endl; } // Create and fill buffer with items. // Nbr items. To be filled in later. uint32 offset = stringItems.getCurrentOffset(); stringItems.writeNextLong(0); uint32 maxCountryMapZoom = 3; uint32 nbrItems = 0; for (uint32 z = 0; z < maxCountryMapZoom; z++) { writeItemsInZoomLevel(theMap, &stringItems, z, nbrItems); } // Fill in nbr items stringItems.writeLong(nbrItems, offset); // Create and fill buffer with version and length DataBuffer versionAndLengthBuffer(8); versionAndLengthBuffer.writeNextLong(theMap->getCreationTime()); uint32 length = idsAndGfx.getCurrentOffset() + stringItems.getCurrentOffset(); versionAndLengthBuffer.writeNextLong(length); // Send the buffers via TCP uint32 nbrBytes = socket->writeAll( versionAndLengthBuffer.getBufferAddress(), versionAndLengthBuffer.getCurrentOffset() ); mc2dbg4 << " Sent " << nbrBytes << " with version (" << theMap->getCreationTime() << ") and length (" << length << ")" << endl; nbrBytes = socket->writeAll( idsAndGfx.getBufferAddress(), idsAndGfx.getCurrentOffset() ); mc2dbg4 << " Sent " << nbrBytes << " with map IDs and GfxData" << endl; nbrBytes = socket->writeAll( stringItems.getBufferAddress(), stringItems.getCurrentOffset() ); mc2dbg4<< " Sent " << nbrBytes << " with string items" << endl; // Delete the socket delete socket; } DEBUG2( mc2dbg << "GfxCountryMapGenerator sent all data for map " << mapIDs[0] << ", processing time " << TimeUtility::getCurrentTime()-startTime << " ms" << endl; );
int setupSockets (BoardDatabase *db, BoardThreadParams threadParams[MAX_N_ROBOTS]) { int i; int Port = 7171; #ifdef IS_WIN int waitResult; WSADATA wsaData; SOCKADDR_IN serverAddr; #else struct sockaddr_in serverAddr; #endif #ifdef IS_WIN if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { return -1; } db->commData.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (db->commData.socket == INVALID_SOCKET) { printf ("Error creating socket %d\n", WSAGetLastError()); WSACleanup(); return -1; } serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(Port); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); #else db->commData.socket = socket(AF_INET, SOCK_STREAM, 0); if (db->commData.socket < 0) { printf ("Error creating socket %d\n", db->commData.socket); return -1; } bzero ((char*)&serverAddr, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(Port); serverAddr.sin_addr.s_addr = INADDR_ANY; #endif #ifdef IS_WIN if (bind (db->commData.socket, (SOCKADDR *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) { printf ("Error binding socket %d\n", WSAGetLastError()); closesocket(db->commData.socket); WSACleanup(); return -1; } if (listen (db->commData.socket, 5) == SOCKET_ERROR) { printf ("Error listening %d\n", WSAGetLastError()); closesocket (db->commData.socket); WSACleanup(); return -1; } #else if (bind (db->commData.socket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { printf ("Error binding socket\n"); closesocket (db->commData.socket); WSACleanup(); return -1; } if (listen (db->commData.socket, 5) != 0) { printf ("Error listening\n"); closesocket (db->commData.socket); WSACleanup(); return -1; } #endif printf ("Blackboard ready.\n"); printf ("Waiting for %d robots to connect.\n", N_ROBOTS); for (i = 0; i < N_ROBOT_THREADS; ++i) // for (i = 0; i < N_ROBOTS; ++i) { threadParams[i] = initBoardThreadParams (db, i); #ifdef IS_WIN waitResult = waitForConnection (db->commData.socket); if (0 > waitResult) { printf ("Error waiting for connection %d\n", waitResult); closesocket (db->commData.socket); WSACleanup(); return -1; } threadParams[i].commData.socket = accept (db->commData.socket, NULL, NULL); if (threadParams[i].commData.socket == SOCKET_ERROR) { printf ("Error accepting connection %d\n", WSAGetLastError()); closesocket (db->commData.socket); WSACleanup(); return -1; } #else threadParams[i].commData.socket = accept(db->commData.socket, NULL, NULL); if (threadParams[i].commData.socket < 0) { printf ("Error accepting connection\n"); return -1; } #endif printf ("Connection received for thread %d.\n", i); } return 1; }
void SocketTransport::listenForClientConnection() { // If there was a previous connection in the base class, shut it down. // This will close the old transport and wait for both the send and receive // worker threads to terminate before proceeding. if (getTransportFd() >= 0) { shutdown(); } VSDebugLogger::Log( VSDebugLogger::LogLevelInfo, "SocketTransport worker thread listening for connections..." ); int abortFd; { Lock lock(m_lock); abortFd = m_abortPipeFd[0]; assertx(abortFd >= 0); } struct addrinfo hint; struct addrinfo* ai = nullptr; std::vector<int> socketFds; memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_UNSPEC; hint.ai_socktype = SOCK_STREAM; hint.ai_flags = AI_PASSIVE; SCOPE_EXIT { if (ai != nullptr) { freeaddrinfo(ai); } for (auto it = socketFds.begin(); it != socketFds.end(); it++) { close(*it); } close(abortFd); m_abortPipeFd[0] = -1; VSDebugLogger::Log( VSDebugLogger::LogLevelInfo, "SocketTransport connection polling thread exiting." ); }; // Share existing DebuggerDisableIPv6 configuration with hphpd. if (RuntimeOption::DebuggerDisableIPv6) { hint.ai_family = AF_INET; } const auto name = RuntimeOption::DebuggerServerIP.empty() ? "localhost" : RuntimeOption::DebuggerServerIP.c_str(); if (getaddrinfo(name, std::to_string(m_listenPort).c_str(), &hint, &ai)) { VSDebugLogger::Log( VSDebugLogger::LogLevelError, "Failed to call getaddrinfo: %d.", errno ); return; } // Attempt to listen on the specified port on each of this host's available // addresses. struct addrinfo* address; bool anyInterfaceBound = false; for (address = ai; address != nullptr; address = address->ai_next) { if (bindAndListen(address, socketFds)) { anyInterfaceBound = true; } } if (!anyInterfaceBound) { VSDebugLogger::Log( VSDebugLogger::LogLevelWarning, "Debugger failed to bind to any interface!" ); return; } else { VSDebugLogger::Log( VSDebugLogger::LogLevelInfo, "Debugger bound to at least one interface." ); } waitForConnection(socketFds, abortFd); }