int main(){ int port = 8888; string ipAddress; bool done; char recMessage[STRLEN]; char sendMessage[STRLEN]; //Client cout<<"Enter an IP address, 127.0.0.1 is the loopback address"<<endl; cin>>ipAddress; ClientSocket sockClient; cout<<"ATTEMPTING TO CONNECT..."<<endl; sockClient.ConnectToServer( ipAddress.c_str(), port ); //Connected while ( !done ){ sockClient.GetAndSendMessage(); cout<<"\t--WAIT--"<<endl; sockClient.RecvData( recMessage, STRLEN ); cout<<"Recv > "<<recMessage<<endl; if ( strcmp( recMessage, "end" ) == 0 || strcmp( sendMessage, "end" ) == 0 ){ done = true; } } sockClient.CloseConnection(); }
bool connect(string address, int port, int attempts = 3) { inactiveTime = 0; ClientSocket* clientSocket = new ClientSocket(); socket = clientSocket; return clientSocket->connect(address, port, attempts); }
void ConnectionManager::handleBadConnections(){ for (int i = 0; i < connections; i++){ if (deviceList[i]->bad){ if (deviceList[i]->attemptReconnect){ ClientSocket* client = dynamic_cast<ClientSocket*>(deviceList[i]); if (client != 0){ client->reconnect(); list[i].fd = client->fd; client->bad = false; } } else { delete deviceList[i]; connections--; deviceList[i] = deviceList[connections]; list[i] = list[connections]; if (i >= 0 && i < connections - 1) i--; } } } badConnections = false; }
void FetchClientPrivate::write_ready() { if (m_postSize == 0) return; char buff[4096]; unsigned tail = m_postSize; if (tail > sizeof(buff)) tail = sizeof(buff); const char *data = m_client->read_data(buff, tail); if (data == NULL){ m_socket->error_state("Read error"); return; } m_postSize -= tail; m_socket->writeBuffer.pack(data, tail); m_socket->write(); if (m_speed){ m_sendSize += tail; time_t now; time(&now); if ((unsigned)now != m_sendTime){ m_sendTime = now; m_sendSize = 0; } if (m_sendSize > (m_speed << 18)){ m_socket->pause(1); return; } } }
void SRVServer::onSocketClosed(MySocket* _pSocket) { ClientSocket* pClientSocket = reinterpret_cast<ClientSocket*>( _pSocket ); int32_t userID = pClientSocket->GetID(); // Send "LEAVE_CHAT" to the Chat Server if(userID >= WS_USERS_AUTO_INCREMENT_OFFSET) { uint32_t logicID = LOGIC_ID_CHESS; TVecChar data; data.assign( (char*)&logicID, (char*)&logicID + sizeof(logicID) ); ClientMsg msg; msg.InitMsg( CHAT, CMD_CHAT_LEAVE, data ); RegInfo regInfo; regInfo.SetID(userID); // simulate a message from the user ClientMsg dummy; Register(&msg, &dummy, ®Info); } }
ClientSocket* ServerSocket::accept(){ LOG_ENTER_FUNC(""); struct sockaddr addr; struct sockaddr_in inaddr; socklen_t socklen = sizeof(addr); int fd = ::accept(this->fd, &addr, &socklen); ClientSocket* cs = NULL; if (fd>=0){ cs = new ClientSocket(); memcpy(&inaddr, &addr, sizeof(inaddr)); cs->setFd(fd); cs->setPort(inaddr.sin_port); cs->setHost(inet_ntoa(inaddr.sin_addr)); cs->setAddr(addr); cs->setInaddr(inaddr); if(this->reuse){ cs->setReuse(true); } if(this->nodelay){ cs->setNodelay(true); } if(this->nonblocking){ cs->setNonblocking(true); } if(this->keepalive){ cs->setKeepalive(true); } } LOG_LEAVE_FUNC(""); return cs; }
void ClientSocketHolder::Update() { //called every 500ms std::lock_guard<std::recursive_mutex> rGuard(m_lock); if(!m_clientSockets.empty()) { time_t t = UNIXTIME; ClientSocketMap::iterator itr, itr2; //ping + process queue for(itr = m_clientSockets.begin();itr != m_clientSockets.end();) { itr2 = itr++; ClientSocket *pSocket = itr2->second; // if(pSocket->m_lastPong < t && ((uint64)(t - pSocket->m_lastPong) > (uint64)g_cfg.PingTimeout)) { Log.Warning(__FUNCTION__, "Connection to client: %s - dropped due to pong timeout.", pSocket->GetRemoteIP().c_str()); pSocket->Disconnect(); continue; } if((uint64)(t - pSocket->m_lastPing) > (uint64)g_cfg.PingSendInterval) { // send a ping packet. pSocket->SendPing(); } //process queue pSocket->ProcessQueue(); } } }
void* native_thread_main(void* data) { CVD::Image<unsigned char> frame_grey = CVD::Image<unsigned char>(CVD::ImageRef(WIDTH, HEIGHT)); pose received_location; received_location.x = 0.0; received_location.y = 0.0; received_location.z = 0.0; received_location.yaw = 0.0; start_time = util_timestamp(); while(true) { //double t1 = util_timestamp(); get_frame_grey(frame_grey.data()); corners.build_from_image(frame_grey, drone_xy_lookup, true);//use_rhips client_socket.sendto(corners, server_addr, server_addr_len); //fprintf(log_file2,"%f,%d\n", (util_timestamp()-t1), corners.size()); pthread_yield(); if(client_socket.recvfrom(command, server_addr, server_addr_len)) { received_location.x = command.packet.transform[0]; received_location.y = command.packet.transform[1]; received_location.z = command.packet.transform[2]; received_location.yaw = command.packet.transform[4]; if(filter_pose(&received_location)) { pthread_mutex_lock(&the_mutex); last_good_location.x = received_location.x; last_good_location.y = received_location.y; last_good_location.z = received_location.z; last_good_location.yaw = received_location.yaw; time_last_good = util_timestamp(); pthread_mutex_unlock(&the_mutex); fprintf(log_file,"%f,%f,%f,%f,%f\n" ,time_last_good // timestamp in sec ,received_location.x // x loction ,received_location.y // y location ,received_location.z // Z location ,received_location.yaw); } } frames_processed++; //printf("found %d corners\n", corners.size()); //printf("estimated pose (x,y,z,yaw): %f, %f, %f, %f\n", received_location.x, received_location.y, received_location.z, received_location.yaw); while(!video_frame_ready()) usleep(50); } }
int main(int argc, char **argv){ int port; string ipAddress; bool done = FALSE; char recMessage[STRLEN]; char sendMessage[STRLEN]; string input; port = atoi(argv[1]); //Client cout<<"Enter an IP address, 127.0.0.1 is the loopback address"<<endl; cin>>ipAddress; ClientSocket sockClient; cout<<"ATTEMPTING TO CONNECT..."<<endl; sockClient.ConnectToServer( ipAddress.c_str(), port ); //Connected //sockClient.RecvData(recMessage, STRLEN);//Get ye here yon connection message //cout << recMessage<<endl; while ( !done ){ //sockClient.GetAndSendMessage(); //Sends input message input = sockClient.UserInput("test.txt"); cout<<"\t--WAIT--"<<endl; sockClient.RecvData( recMessage, STRLEN ); cout<<"Recv > "<<recMessage<<endl; /* if ( strcmp( recMessage, "end" ) == 0 || strcmp( sendMessage, "end" ) == 0 ){ done = true; } */ } sockClient.CloseConnection(); }
ClientSocket *SSLSocketIO::Accept(ListenSocket *s) { if (s->io == &NormalSocketIO) throw SocketException("Attempting to accept on uninitialized socket with SSL"); sockaddrs conaddr; socklen_t size = sizeof(conaddr); int newsock = accept(s->GetFD(), &conaddr.sa, &size); #ifndef INVALID_SOCKET const int INVALID_SOCKET = -1; #endif if (newsock < 0 || newsock == INVALID_SOCKET) throw SocketException("Unable to accept connection: " + Anope::LastError()); ClientSocket *newsocket = s->OnAccept(newsock, conaddr); me->service.Init(newsocket); SSLSocketIO *io = anope_dynamic_static_cast<SSLSocketIO *>(newsocket->io); io->sslsock = SSL_new(server_ctx); if (!io->sslsock) throw SocketException("Unable to initialize SSL socket"); SSL_set_accept_state(io->sslsock); if (!SSL_set_fd(io->sslsock, newsocket->GetFD())) throw SocketException("Unable to set SSL fd"); newsocket->flags[SF_ACCEPTING] = true; this->FinishAccept(newsocket); return newsocket; }
void ServerThread::run(){ ClientSocket *socket = new ClientSocket(this); socket->setSocketDescriptor(socketDescriptor); this->exec(); this->exit(0); }
void TCPServer::incomingConnection(int socketId) { ClientSocket *socket = new ClientSocket(this, m_widget, m_pool); socket->setSocketDescriptor(socketId); QString qstr; qstr += socket->peerAddress().toString(); qstr += ":"; qstr += QString::number(socket->peerPort()); qstr += " 连接上\n"; //m_textEdit->append(qstr); m_widget->writeToEditor(qstr); //m_textEdit->append(QString::fromLocal8Bit("获取CPU使用率失败").append(tr("\n"))); }
ClientSocket* ServerSocket::Accept() { ClientSocket* client = AllocClient(); uv_tcp_init(getSocket()->loop, client->getSocket()); if(uv_accept((uv_stream_t*)getSocket(), (uv_stream_t*) client->getSocket()) == 0) { client->getSocket()->data = client; OnConnection(client); } else { OnError("Accepting Client"); client->Close(); } return client; }
void MyServerSocket::onAccept(sockaddr_in * addr, int handle){ uLong user_id = (addr->sin_addr).s_addr; ClientSocket * socket = createClient((addr->sin_addr).s_addr, inet_ntoa(addr->sin_addr), ntohs(addr->sin_port)); socket->OnAccept(handle); socket->status = socket_ready; socket->s_status = session_connect; /* 成功赋值了 为何?*/ socket->Recevice(); /* add sessions */ //clients.insert(ScoketPair(user_id, socket)); }
int main(){ for(int i = 0; i < 10; i++){ ClientSocket tmp; tmp.Connect("127.0.0.1", 6666); std::string s = randomString(); tmp.WriteLine(s); s = ""; tmp.ReadLine(s); printf("Client : "); tmp.Close(); printf("%d", i); puts(""); } }
//处理新的用户 void MainWindow::onNewConnection(){ QTcpSocket* socket = server->nextPendingConnection(); ClientSocket* cs = new ClientSocket(socket); connect(cs, SIGNAL(showMainWindow(pack_t*)), this, SLOT(toShowMainWindow(pack_t*))); connect(cs, SIGNAL(showMainWindow_string(QString)), this, SLOT(toShowMainWindow_string(QString))); connect(cs, SIGNAL(onlineList_emit(QString)), this, SLOT(solve_onlineListEmit(QString))); connect(cs, SIGNAL(setTextEdit(QString)), this, SLOT(toSetTextEdit(QString))); connect(cs, SIGNAL(sendPackage(pack_t*, QTcpSocket*)), this, SLOT(toSendPackage(pack_t*, QTcpSocket*))); QThread* thread = new QThread(); cs->moveToThread(thread); thread->start(); ui->te_info->append("new connection..."); }
int main(int argc,char **argv) { QApplication app(argc,argv); ClientSocket *socket = new ClientSocket; QObject::connect(socket,SIGNAL(readyRead()),socket,SLOT(readMessage())); socket->connectToHost(QHostAddress::LocalHost, 9999); QPushButton *button = new QPushButton; button->setText("Click"); QObject::connect(button,SIGNAL(clicked()),socket,SLOT(sendMessage())); button->show(); return app.exec(); }
bool FetchClientPrivate::error_state(const char *err, unsigned) { if (m_state == None) return false; if (m_state == Redirect){ if (m_socket){ delete m_socket; m_socket = NULL; } m_code = 0; m_hIn = ""; m_state = None; _fetch(); return false; } if ((m_state != Done) && ((m_state != Data) || (m_size != UNKNOWN_SIZE))){ m_code = 0; log(L_DEBUG, "HTTP: %s", err); } m_bDone = true; m_state = None; if (m_socket) m_socket->close(); return m_client->done(m_code, m_data, m_hIn.c_str()); }
void DVDRemoteApp::sendHttpResponse() { cerr << "SEND HTTP RESPONSE ..." << endl; struct stat statResult; int result = stat("SampleVideo.mp4", &statResult); if (result == -1) perror("stat"); char tbuf[100]; strftime(tbuf, sizeof(tbuf), "%a, %d %b %Y %H:%M:%S %Z", localtime(&statResult.st_mtime)); char cbuf[100]; time_t now = time(NULL); strftime(cbuf, sizeof(cbuf), "%a, %d %b %Y %H:%M:%S %Z", localtime(&now)); stringstream response; if (streamSize == -1) { response << "HTTP/1.1 200 OK\r\n"; // response << "Date: " << cbuf << "\r\n"; response << "Date: Tue, 22 Mar 2016 07:48:09 GMT\r\n"; // response << "Server: DVDServer 0.1\r\n"; response << "Server: Apache/2.4.7 (Ubuntu)\r\n"; // response << "Last-Modified: " << tbuf << "\r\n"; response << "Last-Modified: Mon, 21 Mar 2016 12:10:09 GMT\r\n"; response << "ETag: \"a03275-52e8dfa5d4388\"\r\n"; // response << "Accept-Ranges: bytes\r\n"; response << "Accept-Ranges: none\r\n"; // defines whether the stream supports ranges of data (Seeking) // response << "Transfer-Encoding: chunked\r\n"; // response << "Transfer-coding: chunked\r\n"; response << "Content-Length: " << statResult.st_size << "\r\n"; // response << "Content-Length: " << 0 << "\r\n"; response << "Keep-Alive: timeout=5, max=100\r\n"; response << "Connection: Keep-Alive\r\n"; response << "Content-Type: video/mp4\r\n\r\n"; } else { response << "HTTP/1.1 206 Partial Content\r\n"; // response << "Date: " << cbuf << "\r\n"; response << "Date: Tue, 22 Mar 2016 07:48:09 GMT\r\n"; // response << "Server: DVDServer 0.1\r\n"; response << "Server: Apache/2.4.7 (Ubuntu)\r\n"; // response << "Last-Modified: " << tbuf << "\r\n"; response << "Last-Modified: Mon, 21 Mar 2016 12:10:09 GMT\r\n"; response << "ETag: \"a03275-52e8dfa5d4388\"\r\n"; // response << "Accept-Ranges: bytes\r\n"; response << "Accept-Ranges: none\r\n"; response << "Content-Length: " << streamSize << "\r\n"; response << "Content-Range: bytes " << fileOffset << "-" << fileOffset + streamSize - 1 << "/"<< fileOffset + streamSize << "\r\n"; response << "Keep-Alive: timeout=5, max=100\r\n"; response << "Connection: Keep-Alive\r\n"; response << "Content-Type: video/mp4\r\n\r\n"; } cerr << response.str() << endl; client.writeData((uint8_t*) response.str().c_str(), response.str().length()); //startStream(); startPlay(); }
ClientSocket *SocketIO::Accept(ListenSocket *s) { sockaddrs conaddr; socklen_t size = sizeof(conaddr); int newsock = accept(s->GetFD(), &conaddr.sa, &size); if (newsock >= 0) { ClientSocket *ns = s->OnAccept(newsock, conaddr); ns->flags[SF_ACCEPTED] = true; ns->OnAccept(); return ns; } else throw SocketException("Unable to accept connection: " + Anope::LastError()); }
static void processCommand(ClientSocket &sock) { SyncDocument *doc = trackView->getDocument(); int strLen, serverIndex, newRow; std::string trackName; const sync_track *t; unsigned char cmd = 0; if (sock.recv((char*)&cmd, 1, 0)) { switch (cmd) { case GET_TRACK: // read data sock.recv((char *)&strLen, sizeof(int), 0); strLen = ntohl(strLen); if (!sock.connected()) return; trackName.resize(strLen); if (!sock.recv(&trackName[0], strLen, 0)) return; // find track serverIndex = sync_find_track(doc, trackName.c_str()); if (0 > serverIndex) serverIndex = int(doc->createTrack(trackName)); // setup remap doc->clientSocket.clientTracks[trackName] = clientIndex++; // send key-frames t = doc->tracks[serverIndex]; for (int i = 0; i < (int)t->num_keys; ++i) doc->clientSocket.sendSetKeyCommand(trackName, t->keys[i]); InvalidateRect(trackViewWin, NULL, FALSE); break; case SET_ROW: sock.recv((char*)&newRow, sizeof(int), 0); trackView->setEditRow(ntohl(newRow)); break; } } }
/** Accept a connection from a socket * @param s The socket * @return The new client socket */ ClientSocket *SocketIO::Accept(ListenSocket *s) { sockaddrs conaddr; socklen_t size = sizeof(conaddr); int newsock = accept(s->GetFD(), &conaddr.sa, &size); if (newsock >= 0) { ClientSocket *ns = s->OnAccept(newsock, conaddr); ns->SetStatus(SF_ACCEPTED, true); ns->OnAccept(); return ns; } else throw SocketException(printfify("Unable to accept connection: %s", strerror(errno))); }
int main(int argc, char **argv){ int port; string ipAddress = "127.0.0.1"; //bool done = FALSE; char recMessage[STRLEN] = "\0"; char sendMessage[STRLEN]; //Client cout<<"Enter an IP address, 127.0.0.1 is the loopback address"<<endl; //cin>>ipAddress; ClientSocket sockClient; //port = atoi(argv[1]); cout << "AND AWAY WE GO!\n"; sockClient.KnockKnock( ipAddress.c_str()); sockClient.CloseConnection(); system("pause"); }
void initnative() { corners.erase(); the_corners.set_max_size(16); the_corner_scores.set_max_size(16); the_max_corners.set_max_size(16); the_max_corner_descriptors.set_max_size(16); drone_xy_lookup = Image<TooN::Vector<2, float> >(ImageRef(WIDTH, HEIGHT)); std::ifstream is; is.open("dronecamparameters.txt"); drone_camera_model.load(is); is.close(); //TooN::Vector<6> cam_params = drone_camera_model.get_parameters(); //printf("cam params: %f %f %f %f %f %f\n", cam_params[0], cam_params[1], cam_params[2], cam_params[3], cam_params[4], cam_params[5]); generate_xy_lookup(drone_camera_model, drone_xy_lookup); client_socket.create(serverip, serverport); log_file = fopen("udp_logX.csv", "wb"); if(log_file==NULL) { printf("File 2 open failed\n"); } fprintf(log_file,"Time,X (m),Y (m),Z (m),Yaw (rad)\n"); /*log_file2 = fopen("udp_log2.csv", "wb"); if(log_file2==NULL) { printf("File 3 open failed\n"); } fprintf(log_file2,"Time,Corners\n");*/ //init front camera while(video_init((char*) "/dev/video1", WIDTH, HEIGHT, 30)) { printf("Camera initialisation failed. Retry in 2 seconds...\n"); sleep(2); } printf("video_init completed\n"); sleep(2); int rc = pthread_create(&native_thread, NULL, native_thread_main, NULL); if (rc) printf("ctl_Init: Return code from pthread_create(native_thread) is %d\n", rc); last_good_location.x = 0.0; last_good_location.y = 0.0; last_good_location.z = 0.0; last_good_location.yaw = 0.0; printf("native_init completed\n"); }
void Server::incomingConnection(int handle) { qDebug() << "Connected"; ClientSocket *client = new ClientSocket(this); client->setSocketDescriptor(handle); connect(client, SIGNAL(onRegisterRequest(QString,QString)), accountManager, SLOT(Registration(QString,QString))); connect(client, SIGNAL(onLoginRequest(QString,QString)), accountManager, SLOT(Login(QString,QString))); connect(client, SIGNAL(onJoinGameRequest(UserInfo*)), game, SLOT(joinGame(UserInfo*))); connect(game, SIGNAL(onUserJoinGame(QList<UserInfo>)), client, SLOT(doUserJoinGame(QList<UserInfo>))); connect(game, SIGNAL(gameStarted(GameStartAction)), client, SLOT(doGameStart(GameStartAction))); connect(game, SIGNAL(onUserMove(UserMoveAction)), client, SLOT(doUserMove(UserMoveAction))); connect(game, SIGNAL(onUserAction(UserAction)), client, SLOT(doUserAction(UserAction))); connect(game, SIGNAL(onBankChanged(BankChangeAction)), client, SLOT(doBankChangeAction(BankChangeAction))); connect(game, SIGNAL(onFirstCardsDealed(FirstCardsAction)), client, SLOT(doFirstCardsAction(FirstCardsAction))); connect(game, SIGNAL(onNextCardDealed(Card)), client, SLOT(doNextCardsDealed(Card))); connect(game, SIGNAL(onGameFinished(GameFinish)), client, SLOT(doGameFinished(GameFinish))); connect(client, SIGNAL(onUserAction(UserAction)), game, SLOT(doAction(UserAction))); }
void SRVServer::RemoveSocket( MySocket* _pSocket ) { ClientSocket* pClientSocket = reinterpret_cast<ClientSocket*>( _pSocket ); int32_t userID = 0; if( pClientSocket && ( userID = pClientSocket->GetID()) ) { m_pOnLineManager->OffLine( userID ); } #ifdef LOW_LEVEL_DEBUG cout << "SOCKET " << _pSocket->GetSocket() << " SRVServer::RemoveSocket. DELETE SOCKET" << endl; #endif SocketManager::RemoveSocket( _pSocket ); }
bool Packet::CreateFromSocket (ClientSocket& socket) { if (!socket.Receive (*this)) return false; type_ = ReadPacketType (); return true; }
void close() { currentConnectionServer = ""; currentConnectionPort = 0; proxyServerName = ""; proxyServerPort = 0; socket.close(); property = HTTPProperty(); }
void connect(const char* serverName, unsigned short portNumber) { // set option. setHostName(serverName); currentConnectionPort = portNumber; // open TCP connection. socket.connect(IP(serverName, portNumber)); }
void Tick() { for (unsigned i = servers.size(); i > 0; --i) { HTTPServer *s = servers[i - 1]; for (std::set<ClientSocket *>::iterator it = s->clients.begin(), it_end = s->clients.end(); it != it_end;) { ClientSocket *sock = *it; ++it; if (Sinkhole::curtime > sock->connected + s->timeout) { Sinkhole::Log(s->name, sock->GetIP(), "TIMEOUT"); delete sock; } } } }