int RecordProcessor::recycle() { // TODO: sLog.trace("Recycle %d from: %s\n", _type, sock()->getRemoteIp()); return 1; }
void o3d3xx::FrameGrabber::Run() { boost::asio::io_service::work work(this->io_service_); // // setup the camera for image acquistion // std::string cam_ip; int cam_port; try { cam_ip = this->cam_->GetIP(); cam_port = std::stoi(this->cam_->GetParameter("PcicTcpPort")); } catch (const o3d3xx::error_t& ex) { LOG(ERROR) << "Could not get IP/Port of the camera: " << ex.what(); return; } LOG(INFO) << "Camera connection info: ip=" << cam_ip << ", port=" << cam_port; try { this->cam_->RequestSession(); this->cam_->SetOperatingMode(o3d3xx::Camera::operating_mode::RUN); this->cam_->CancelSession(); } catch (const o3d3xx::error_t& ex) { LOG(ERROR) << "Failed to setup camera for image acquisition: " << ex.what(); return; } // // init the asio structures // boost::asio::ip::tcp::socket sock(this->io_service_); boost::asio::ip::tcp::endpoint endpoint( boost::asio::ip::address::from_string(cam_ip), cam_port); // // Forward declare our two read handlers (because they need to call // eachother). // o3d3xx::FrameGrabber::ReadHandler ticket_handler; o3d3xx::FrameGrabber::ReadHandler image_handler; // // image data callback // std::size_t bytes_read = 0; std::size_t buff_sz = 0; // bytes image_handler = [&, this] (const boost::system::error_code& ec, std::size_t bytes_transferred) { if (ec) { throw o3d3xx::error_t(ec.value()); } bytes_read += bytes_transferred; //DLOG(INFO) << "Read " << bytes_read << " image bytes of " // << buff_sz; if (bytes_read == buff_sz) { DLOG(INFO) << "Got full image!"; bytes_read = 0; // 1. verify the data if (o3d3xx::verify_image_buffer(this->back_buffer_)) { DLOG(INFO) << "Image OK"; // 2. move the data to the front buffer in O(1) time complexity this->front_buffer_mutex_.lock(); this->back_buffer_.swap(this->front_buffer_); this->front_buffer_mutex_.unlock(); // 3. notify waiting clients this->front_buffer_cv_.notify_all(); } else { LOG(WARNING) << "Bad image!"; } // read another ticket sock.async_read_some( boost::asio::buffer(this->ticket_buffer_.data(), o3d3xx::IMG_TICKET_SZ), ticket_handler); return; } sock.async_read_some( boost::asio::buffer(&this->back_buffer_[bytes_read], buff_sz - bytes_read), image_handler); }; // // ticket callback // std::size_t ticket_bytes_read = 0; std::size_t ticket_buff_sz = o3d3xx::IMG_TICKET_SZ; this->ticket_buffer_.resize(ticket_buff_sz); ticket_handler = [&, this] (const boost::system::error_code& ec, std::size_t bytes_transferred) { if (ec) { throw o3d3xx::error_t(ec.value()); } ticket_bytes_read += bytes_transferred; DLOG(INFO) << "Read " << ticket_bytes_read << " ticket bytes of " << ticket_buff_sz; if (ticket_bytes_read == ticket_buff_sz) { DLOG(INFO) << "Got full ticket!"; ticket_bytes_read = 0; if (o3d3xx::verify_ticket_buffer(this->ticket_buffer_)) { DLOG(INFO) << "Ticket OK"; buff_sz = o3d3xx::get_image_buffer_size(this->ticket_buffer_); DLOG(INFO) << "Image buffer size: " << buff_sz; this->back_buffer_.resize(buff_sz); sock.async_read_some( boost::asio::buffer(this->back_buffer_.data(), buff_sz), image_handler); return; } LOG(WARNING) << "Bad ticket!"; } sock.async_read_some( boost::asio::buffer(&this->ticket_buffer_[ticket_bytes_read], ticket_buff_sz - ticket_bytes_read), ticket_handler); }; // // connect to the sensor and start streaming in image data // try { sock.async_connect(endpoint, [&, this] (const boost::system::error_code& ec) { if (ec) { throw o3d3xx::error_t(ec.value()); } sock.async_read_some( boost::asio::buffer( this->ticket_buffer_.data(), ticket_buff_sz), ticket_handler); }); this->io_service_.run(); } catch (const std::exception& ex) { // // In here we should discern why the exception with thrown. // // Special case the "Stop()" request from the control thread // LOG(WARNING) << "Exception: " << ex.what(); } LOG(INFO) << "Framegrabber thread done."; }
void *CUpdateSystem::dlRev(void *argv) { CUpdateSystem *pUpdateSystem = (CUpdateSystem *) argv; // get server first const char strUrl[] = URL_REV; // filter http:// const char *pSlash = NULL; const char *pUrl = strUrl; if( !strncmp(strUrl, "http://", 7) ) pUrl += 7; pSlash = strchr(pUrl, '/'); if( pSlash == NULL ) return NULL; // no filepath to download size_t iLenServer = pSlash - pUrl; char *strServer = new char[iLenServer+1]; memcpy(strServer, pUrl, iLenServer); strServer[iLenServer] = 0; // get filepath const char *pFilePath = pSlash; // printf("%s %s\n", strServer, pFilePath); CSockTCP sock(strServer, 80); if( !sock._connect() ) { printf("[SBG]: Could not connect to host.\n"); return NULL; } if( !sock.isReadyWrite(2) ) return NULL; sock.sendMsg(CStr::format("GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", pFilePath, strServer)); // sock.sendMsg("GET /sbguardian2/rev.txt HTTP/1.1\r\nHost: http://storage.steambans.com\r\n\r\n"); delete[] strServer; strServer = NULL; // parse header const char *strLine = sock.readLine(); if( strLine == NULL ) { printf("[SBG]: Error: no data received.\n"); return false; } int iStatus = 0; sscanf(strLine, "HTTP/1.1 %d", &iStatus); if( iStatus != 200 ) { // not OK switch( iStatus ) { printf("[SBG]: HTTP Status not OK.\n"); case 404: // file not found printf("[SBG]: HTTP-Error: File not found.\n"); break; } // get the rest while( sock.isReadReady(2) ) { sock.read(); } return false; } size_t iLen = 0; while( 1 ) { strLine = sock.readLine(); if( strLine == NULL ) return false; // should not happen if( strLine[1] == '\n' ) // \r\n break; if( strstr(strLine, "Content-Length: ") != NULL ) { iLen = atoi(strLine+16); } } if( iLen == 0 ) return NULL; size_t iBitsRead = sock.read(); if( iLen != iBitsRead ) return NULL; pUpdateSystem->m_iHeadRev = atoi(sock.data()); printf("[SBG]: HeadRev: %d\n", pUpdateSystem->m_iHeadRev); if( pUpdateSystem->m_iHeadRev <= REV ) return NULL; CFileMgr::log(pUpdateSystem->getName(), "A new version is available"); pUpdateSystem->m_pEngine->printHud("[SBG]: A new version available..."); #ifdef STANDALONE // hl1 standalone cant download and reload return NULL; #endif CFileMgr::log(pUpdateSystem->getName(), "Downloading the new version..."); pUpdateSystem->m_pEngine->printHud("[SBG]: Downloading the new version..."); if( CSockTCP::download(DL_FILE, CStr::format("%s", pUpdateSystem->m_strPath)) ) { printf("[SBG]: downloaded the update.\n"); CFileMgr::log(pUpdateSystem->getName(), "Download was successfully."); CBuf bufDl, bufNew, bufTmp; bufDl.thisFormat("%s%s", pUpdateSystem->m_strPath, _DL_FILE _EXT); bufNew.thisFormat("%s%s", pUpdateSystem->m_strPath, pUpdateSystem->m_strFile); bufTmp.thisFormat("%s" S_TMPNAME, pUpdateSystem->m_strPath); CFileMgr::Rename(bufNew.data(), bufTmp.data()); CFileMgr::Rename(bufDl.data(), bufNew.data()); pUpdateSystem->m_bReload = true; } else { printf("[SBG]: Could not download the files.\n"); CFileMgr::log(pUpdateSystem->getName(), "Download failed."); } return NULL; }
bool Accueil::download(QString url, QString destPath, QString filename, bool justCheck) { Q_UNUSED(filename); QString host = url; QString reqPath; int port = 80; if(url.startsWith("http://")) { host.remove(0, 7); } int colonIndex = host.indexOf(':'); int slashIndex = host.indexOf('/'); if(slashIndex < 0) { return false; } reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); host = host.left(slashIndex); if(colonIndex > 0) { QString portStr = host.right(host.length() - colonIndex - 1); host = host.left(colonIndex); port = portStr.toInt(0, 10); } connect: QTcpSocket sock(this); sock.setReadBufferSize(65535); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { QMessageBox::critical(this, tr("qmplayer"), sock.errorString()); return false; } QByteArray req("GET "); req.append(reqPath); req.append(" HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); int contentLen = 0; bool html = false; QByteArray line; for(;;) { line = sock.readLine(); if(line.isEmpty()) { if(sock.waitForReadyRead(5000)) { continue; } break; } if(line.trimmed().isEmpty()) { break; } html = html | (line.indexOf("Content-Type: text/html") == 0); if(line.indexOf("Content-Length: ") == 0) { contentLen = line.remove(0, 16).trimmed().toInt(0, 10); } } if(html) { QByteArray text = sock.readAll(); sock.close(); if(text.length() == 0) { QMessageBox::critical(this, tr("qmplayer"), tr("No response from ") + host); return false; } text.replace("</br>", "\n"); if(QMessageBox::information(this, "qmplayer", text, QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) { goto connect; } return false; } else if(justCheck) { sock.close(); return true; } QFile f(destPath); if(!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("qmplayer"), tr("Unable to save file:\r\n\r\n") + f.errorString()); sock.close(); return false; } #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); #endif if(contentLen <= 0) { contentLen = 1024 * 1024; } int remains = contentLen; char buf[65535]; int count; bool abort = false; for(;;) { QApplication::processEvents(); if(abort) { break; } if(sock.bytesAvailable() < 65535 && sock.state() == QAbstractSocket::ConnectedState) { sock.waitForReadyRead(1000); continue; } count = sock.read(buf, 65535); if(count <= 0) { break; } f.write(buf, count); f.flush(); remains -= count; if(remains <= 0) { remains = contentLen; } } f.close(); sock.close(); #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); #endif return true; }
bool QMplayer::runClient() { if(tcpServer != NULL) { QMessageBox::critical(this, tr("qmplayer"), tr("Point your web browser to http://localhost:7654 (replace localhost with this computer IP address)")); return true; } if(screen != QMplayer::ScreenConnect) { lineEdit->setText("192.168.0.200:7654"); showScreen(QMplayer::ScreenConnect); return true; } showScreen(QMplayer::ScreenInit); QString host = lineEdit->text(); int port = 80; int colonIndex = host.indexOf(':'); if(colonIndex > 0) { port = host.right(host.length() - colonIndex - 1).toInt(0, 10); host = host.remove(colonIndex, host.length() - colonIndex); } QTcpSocket sock(this); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { QMessageBox::critical(this, tr("qmplayer"), sock.errorString()); return true; } QByteArray req("GET / HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); QByteArray res; while(sock.waitForReadyRead(5000)) { res += sock.readAll(); } sock.close(); if(res.length() == 0) { QMessageBox::critical(this, tr("qmplayer"), tr("No response from ") + host); return true; } delItems(lw); QTextStream buf(&res); buf.setCodec(QTextCodec::codecForName("utf8")); QString line; QString dir; for(;;) { line = buf.readLine(); if(line.isNull()) { break; } if(line.indexOf("<a href=\"http://") == 0) { int urlEnd = line.indexOf('"', 17); if(urlEnd < 0) { continue; } QString url = line.mid(9, urlEnd - 9); int start = url.lastIndexOf('/'); if(start < 0) { continue; } for(int i = start - 1; i >= 0; i--) { if(dir.length() <= i || dir.at(i) != url.at(i)) { dir = url.left(start); lw->addItem(getDirItem(lw, dir)); break; } } int fileStart = line.indexOf('>', 17) + 1; int fileEnd = line.indexOf('<', 17); if(fileStart <= 17 || fileEnd <= 17 || fileEnd < fileStart) { continue; } QString file = line.mid(fileStart, fileEnd - fileStart); lw->addItem(file); } } return true; }
void clientSocket::init() { const int RCVBUFSIZE = 256; // Size of receive buffer cout << "Conecting on server as: " << getAddress() << " on port: " << getPort() << endl; string servAddress = getAddress(); char *echoString = getSend(); int echoStringLen = strlen(echoString); // Determine input length unsigned short echoServPort = getPort(); try { // Establish connection with the echo server TCPSocket sock(servAddress, echoServPort); // Send the string to the echo server sock.send(echoString, echoStringLen); char echoBuffer[RCVBUFSIZE + 1]; // Buffer for echo string + \0 int bytesReceived = 0; // Bytes read on each recv() int totalBytesReceived = 0; // Total bytes read // Receive the same string back from the server cout << "Received: "; // Setup to print the echoed string while (totalBytesReceived < echoStringLen) { // Receive up to the buffer size bytes from the sender if ((bytesReceived = (sock.recv(echoBuffer, RCVBUFSIZE))) <= 0) { cerr << "Unable to read"; exit(1); } totalBytesReceived += bytesReceived; // Keep tally of total bytes echoBuffer[bytesReceived] = '\0'; // Terminate the string! cout << echoBuffer; // Print the echo buffer } cout << endl; // Destructor closes the socket } catch (SocketException &e) { cerr << e.what() << endl; exit(1); } }
int main(int argc, char* argv[]){ if(argc <= 2){ printf("usage: %s ip_address port_number\n", argv[0]); return 1; } const char* ip = argv[1]; int port = atoi(argv[2]); struct sockaddr_in server_address; bzero(&server_address, sizeof(server_address)); server_address.sin_family = AF_INET; inet_pton(AF_INET, ip, &server_address.sin_addr); server_address.sin_port = htons(port); int sockfd = sock(PF_INET, SOCK_STREAM, 0); assert(sockfd >= 0); if(connect(sockfd, (struct sockaddr*)&server_address, sizeof(server_address)) < 0){ printf("connection failed\n"); close(sockfd); return 1; } pollfd fds[2]; fds[0].fd = 0; fds[0].events = POLLIN; fds[0].revents = 0; fds[1].fd = sockfd; fds[1].events = POLLIN | POLLRDHUP; fds[1].revents = 0; char buf[BUFFER_SIZE]; int pipefd[2]; int ret = pipe(pipefd); assert(ret != -1); while(1){ int ret = poll(fds, 2, -1); if(ret < 0){ printf("poll failure\n"); break; } if(fds[1].revents & POLLRDHUP){ /*连接被对方关闭,或被对方关闭了写操作*/ printf("server close the connection\n"); break; } if(fds[1].revents & POLLIN){ memset(buf, '\0', BUFFER_SIZE); recv(fds[1].fd, buf, BUFFER_SIZE - 1, 0); printf("%s\n", buf); } if(fds[0].revents & POLLIN){ /*使用splice将用户输入的数据直接写到sockfd上(零拷贝)*/ splice(0, NULL, pipefd[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE); splice(pipefd[0], NULL, sockfd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE); } } close(sockfd); return 0; }
void MMyLib::MyServer::start() { sock_pt sock(new ip::tcp::socket(ios)); acceptor.async_accept(*sock, boost::bind(&MyServer::accept_handler, this, boost::asio::placeholders::error, sock)); }
void MMyLib::MyClient::start() { sock_pt sock(new ip::tcp::socket(ios)); sock->async_connect(ep, boost::bind(&MyClient::conn_handler, this, boost::asio::placeholders::error, sock)); }
bool QDictWidget::download(QString url, QString destPath, QString filename) { browser->setText(tr("Downloading") + " " + filename); QString host = url; QString reqPath; int port = 80; if(url.startsWith("http://")) { host.remove(0, 7); } int colonIndex = host.indexOf(':'); int slashIndex = host.indexOf('/'); if(slashIndex < 0) { return false; } reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); host = host.left(slashIndex); if(colonIndex > 0) { QString portStr = host.right(host.length() - colonIndex - 1); host = host.left(colonIndex); port = portStr.toInt(0, 10); } connect: QTcpSocket sock(this); sock.setReadBufferSize(65535); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { showErr(sock.errorString()); return false; } QByteArray req("GET "); req.append(reqPath); req.append(" HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); int contentLen = 0; bool html = false; QByteArray line; for(;;) { line = sock.readLine(); if(line.isEmpty()) { if(sock.waitForReadyRead(5000)) { continue; } break; } if(line.trimmed().isEmpty()) { break; } html = html | (line.indexOf("Content-Type: text/html") == 0); if(line.indexOf("Content-Length: ") == 0) { contentLen = line.remove(0, 16).trimmed().toInt(0, 10); } } if(html) { QByteArray text = sock.readAll(); sock.close(); if(text.length() == 0) { QMessageBox::critical(this, tr("English dictionary"), tr("No response from ") + host); return false; } text.replace("</br>", "\n"); if(QMessageBox::information(this, tr("English dictionary"), text, QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) { goto connect; } return false; } QFile f(destPath); if(!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("English dictionary"), tr("Unable to save file:\r\n\r\n") + f.errorString()); sock.close(); return false; } #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); #endif if(contentLen <= 0) { QMessageBox::critical(this, tr("English dictionary"), tr("Couldnt read content length")); contentLen = 0x7fffffff; } progress->setMaximum(contentLen); progress->setValue(0); int remains = contentLen; char buf[65535]; int count; for(;;) { QApplication::processEvents(); count = sock.read(buf, 65535); if(count < 0) { break; } f.write(buf, count); f.flush(); remains -= count; if(remains <= 0) { break; } progress->setValue(contentLen - remains); } f.close(); sock.close(); #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); #endif return true; }
int pmdTcpListenerEntryPoint () { int rc = EDB_OK ; int port = 48127 ; ossSocket sock ( port ) ; rc = sock.initSocket () ; if ( rc ) { printf ( "Failed to initailize socket, rc = %d", rc ) ; goto error ; } rc = sock.bind_listen () ; if ( rc ) { printf ( "Failed to bind/listen socket, rc = %d", rc ) ; goto error ; } // master loop for tcp listener while ( true ) { int s ; rc = sock.accept ( &s, NULL, NULL ) ; // if we don't get anything from period of time, let's loop if ( EDB_TIMEOUT == rc ) { rc = EDB_OK ; continue ; } char buffer [1024] ; int size ; ossSocket sock1 ( &s ) ; sock1.disableNagle () ; do { rc = sock1.recv ( ( char*)&size, 4 ) ; if ( rc && rc != EDB_TIMEOUT ) { printf ( "Failed to receive size, rc = %d", rc ) ; goto error ; } } while ( EDB_TIMEOUT == rc ) ; do { rc = sock1.recv ( &buffer[0], size-sizeof(int) ) ; if ( rc && rc != EDB_TIMEOUT ) { printf ( "Failed to receive buffer, rc = %d", rc ) ; goto error ; } } while ( EDB_TIMEOUT == rc ) ; printf ( "%s\n", buffer ) ; sock1.close () ; } done : return rc ; error : switch ( rc ) { case EDB_SYS : printf ( "SYstem error occured" ) ; break ; default : printf ( "Internal error" ) ; } goto done ; }