// //finds the highest socket number and sets the rset and wset bits //from our list of clients and our listening socket. // int SimpleServer::getMaxFD() { int imax = m_sListen; ServerSocket* s; FD_ZERO(&m_wset); FD_ZERO(&m_rset); if(!m_bUsingThread) { //when we are using threads, this simple server object is only //paying attention to one socket. Other simple server objects //will pay attention to other sockets. Listen socket is taken //care of in the manager. FD_SET(m_sListen,&m_rset); //select on listening socket } for(s = m_listClients.getHead(); s; s = m_listClients.getNext()) { FD_SET(*s,&m_rset); //select for readability if(s->getOutBufferSize()) FD_SET(*s,&m_wset); //need to send data out, select for writability if((int)(*s) > imax) imax = *s; } return imax; }
void TelnetServer::start( int port ) { Socket::Address addr( port ); mSocket.bind( addr ); mSocket.listen( 5 ); mSocket.setSelector( this, &mSelector ); }
int main(int argc, const char * argv[]) { m_g = make_shared<Game>(Game()); // start command consumer thread thread consumer {consume_command}; // keep client threads here, so we don't need to detach them vector<thread> handlers; // create a server socket ServerSocket server {machiavelli::tcp_port}; while (true) { try { while (true) { // wait for connection from client; will create new socket cerr << "server listening" << '\n'; unique_ptr<Socket> client {server.accept()}; // communicate with client over new socket in separate thread thread handler {handle_client, move(client)}; handlers.push_back(move(handler)); } } catch (const exception& ex) { cerr << ex.what() << ", resuming..." << '\n'; } catch (...) { cerr << "problems, problems, but: keep calm and carry on!\n"; } } return 0; }
int main() { /* StdWriteRead stdWriteRead; runloop.registerReadIntent(fileno(stdin), &stdWriteRead); runloop.run(); */ /* try { RunLoop runloop; Socket socket; socket.connect("localhost", 22, false); int sock = socket.getSocket(); StdWriteRead stdWriteRead(sock); runloop.registerReadIntent(sock, &stdWriteRead); runloop.run(); } catch ( std::runtime_error r ) { fprintf(stderr, r.what()); } */ ServerSocket serverSocket; serverSocket.listen("0.0.0.0", 3000, 10); std::string ip; serverSocket.accept(&ip, NULL); printf("socket: %s\n", ip.c_str()); }
int main (int argc, char* argv[]) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = &sig_handler; sigaction(SIGINT, &sa, NULL); IniParser* ini = new IniParser("server.ini"); documentRoot = ini->get("document_root"); std::string port = ini->get("port"); delete(ini); ServerSocket* server = new ServerSocket(port); ClientSocket* client = NULL; while (!stop) { client = server->accept(true); if (client != NULL) { pthread_t tid; pthread_create(&tid, NULL, &clientThread, client); pthread_detach(tid); } } delete(server); std::cout << "Shutdown complete." << std::endl; return 0; }
int main(){ Database db("database"); //listening requests try{ // Create the socket ServerSocket server ( 30000 ); while(true){ ServerSocket new_sock; server.accept (new_sock); try{ std::string data; new_sock >> data; std::string *res = db.request(data); new_sock << *res; delete res; }catch (SocketException& e){ std::cout << "Something go wrong: " << e.description() << "\nExiting.\n"; } } } catch (SocketException& e){ std::cout << "Something go wrong: " << e.description() << "\nExiting.\n"; } return 0; }
bool accept(int port, string address = "0") { inactiveTime = 0; ServerSocket* serverSocket = new ServerSocket(); socket = serverSocket; return serverSocket->accept(port, address); }
int main ( int argc, int argv[] ) { std::cout << "running....\n"; try { // Create the socket ServerSocket server ( 6006 ); while ( true ) { ServerSocket new_sock; server.accept ( new_sock ); try { while ( true ) { char *data; //new_sock >> data; new_sock << "Mesaje"; } } catch ( SocketException& ) {} } } catch ( SocketException& e ) { cout << "Exception was caught:" << e.description() << "\nExiting.\n"; } return 0; }
void LoginServer::Run(LoginServer *Instance) { ServerSocket runningSocket; if (runningSocket.Configure(Instance->m_ServerPort) == false) { printf("Unable to establish server socket, there is an issue with the server.\n"); return; } while (Instance->m_Running) { /* * Listen For New Connections. */ ClientConnection baseClient = runningSocket.Accept(); LoginClient* client = new LoginClient(baseClient); /* * Lock client array and place the client in the queue */ Instance->m_ClientsLock.lock(); Instance->m_Clients.push_back(client); Instance->m_ClientsLock.unlock(); } runningSocket.Flush(); }
void IOUtil::createSocketPair(int pair[2]) throw (IOException&) { #if defined(WIN32) Socket connectSocket; Socket serverClientSocket; ServerSocket listenSocket; SocketAddress loopback = SocketAddress::loopback(AF_INET, 0); listenSocket.listen(loopback, 5, false); connectSocket.connect(listenSocket.getLocalAddress(), true); if (!listenSocket.accept(serverClientSocket)) { THROW2(IOException, "Can't accept for socket pair"); } pair[0] = connectSocket.detach(); pair[1] = serverClientSocket.detach(); #else if (0 != ::socketpair(AF_LOCAL, SOCK_STREAM, 0, pair)) { THROW2(IOException, "Can't create socket pair"); } #endif }
int main (){ cout << "server running...." << endl; try{ ServerSocket server ( 30000 ); // Create main server socket while ( true ){ // server runs forever ServerSocket new_sock; // bind user socket to port and listen server.accept ( new_sock ); printUsage(); try{ while ( true ){ char command[256]; //user input string reply; //command from client cout << "> "; cin.getline(command,256); if (strlen(command) == 0) //re-prompt user if input is empty continue; new_sock << string(command); //send command to create new_sock >> reply; //read confirmation cout << reply <<endl; } }catch ( SocketException& ) {} } } catch ( SocketException& e ){ cout << "Exception was caught:" << e.description() << endl << "Exiting."; } return 0; }
bool handle_web_request(void * args){ //get arguments void **ar = (void **) args; ServerSocket *serverSocket = (ServerSocket *) ar[0]; int client_file_descriptor = *((int *) ar[1]); char *buffer = (char *) ar[2]; //================================================= cout << "===========================" << endl; cout << "raw data : " << buffer << endl; //TODO:: optimize this (copy the whole buffer into string) string data(buffer); try{ ServerManager server_manager(data); string response; server_manager.handle_request(&response); std::vector<char> writable(response.size()+1); std::copy(response.begin(), response.end(), writable.begin()); writable[response.size()] = '\0'; //@Moustafa: please change to const char * instead of char * serverSocket->writeToSocket(&writable[0], args); HttpGetRequestParser request(data); cout << "Required file : " << request.getRequiredFileName() << endl; map<string,string> *m = request.getParameters(); map<string,string>::iterator it = m->begin(); cout << "parameters : " << endl; for (;it != m->end();it++) cout << it->first << " = " << request.getParameter(it->first) << endl; }catch(int e){ return false; } //================================================= //close the connection after returning the required object if(serverSocket->getConnectionType() == SOCK_STREAM) close(client_file_descriptor); return true; }
void KeyValueStore::InternalThread::incomingRoutine() { const Config::ServerInformation& info = config.getServerInformation(); Config::ThreadControl& control = config.getThreadControl(); Mutex& inMutex = control.getInMutex(); Condition& cond = control.getInCondition(); Thread incoming; Incoming inTask; int currId = -1; static bool first = true; // Init connection info SocketAddress sock(info.address, info.internalPort); ServerSocket server; try { server.bind(sock, true); server.listen(5); } catch(Exception& e) { printKv("Could not initialize internal thread, please restart server ("<< e.displayText()<< ")"); } StreamSocket client; while(control.isLive()) { inMutex.lock(); cond.wait(inMutex); unsigned nextId = control.getConnectedId(); inMutex.unlock(); // NOTE: From a security perspective this is not safe. // if someone tries to connect at the same time a rejoin // was initiated, they could easily perform a MITM attack. // However, since this is an academic exercise, I am not too // concerned with security (as can be seen by many other components // in this system as well). if(currId != (int)nextId) { currId = nextId; // TODO: Update processing thread somehow printKv("Told a new server should be connecting..."); try { client = server.acceptConnection(); printKv("Incoming server connected: "<< currId); inTask.cancel(); if(!first) incoming.join(); first = false; inTask = Incoming(client, &config.getThreadControl()); incoming.start(inTask); printKv("Handling new server"); } catch(TimeoutException& e) { printKv("Server did not connect in time - we don't want the system to be hung up, though ("<< e.displayText() <<")"); } } } server.close(); }
void SocketTest::testConnect() { ServerSocket serv; serv.bind(SocketAddress()); serv.listen(); StreamSocket ss; Timespan timeout(250000); ss.connect(SocketAddress("localhost", serv.address().port()), timeout); }
static int _main(int argc, char **argv) { vector<string> args(argc-1); for (int i=1; i<argc; ++i) { args[i-1] = argv[i]; } args.at(0); //YaoProtocol yao; Socket *s; ifstream fmtin("/home/louis/sfe/priveq.fmt"); FmtFile fmt = FmtFile::parseFmt(fmtin); cout << "Read fmt file" << endl; ifstream in("/home/louis/sfe/priveq.circ"); Circuit_p cc = Circuit::parseCirc(in); if (args[0] == ("A")) { args.at(1); BigInt n = BigInt::parseString(args[1]); bit_vector input_bits = toBits(n, fmt.numInputs(0)); cout << "connecting" << endl; s = new Socket("localhost", 5437); DataOutput *out = s->getOutput(); DataInput *in = s->getInput(); YaoSender cli; cli.setStreams(in, out); cli.go(cc, fmt, input_bits); delete out; delete in; delete s; } else if (args[0] == ("B")) { args.at(1); BigInt n = BigInt::parseString(args[1]); bit_vector input_bits = toBits(n, fmt.numInputs(1)); args.at(1); YaoChooser srv; cout << "listening" << endl; ServerSocket *ss = new ServerSocket(5437); s = ss->accept(); DataOutput *out = s->getOutput(); DataInput *in = s->getInput(); srv.setStreams(in, out); bit_vector circ_out = srv.go(cc, fmt, input_bits); for (uint i=0; i<circ_out.size(); ++i) { cout << "output " << i << ": " << circ_out[i] << endl; } delete s; delete ss; delete out; delete in; } return 0; }
virtual void run(){ try{ unsigned char buf[1000]; ServerSocket server; server.bind( "127.0.0.1", SocketFactoryTest::DEFAULT_PORT ); net::Socket* socket = server.accept(); server.close(); socket->setSoLinger( false, 0 ); synchronized(&mutex) { numClients++; mutex.notifyAll(); } while( !done && socket != NULL ){ io::InputStream* stream = socket->getInputStream(); memset( buf, 0, 1000 ); try{ if( stream->read( buf, 1000, 0, 1000 ) == -1 ) { done = true; continue; } lastMessage = (char*)buf; if( strcmp( (char*)buf, "reply" ) == 0 ){ io::OutputStream* output = socket->getOutputStream(); output->write( (unsigned char*)"hello", (int)strlen("hello"), 0, (int)strlen("hello") ); } }catch( io::IOException& ex ){ done = true; } } socket->close(); delete socket; numClients--; synchronized(&mutex) { mutex.notifyAll(); } }catch( io::IOException& ex ){ printf("%s\n", ex.getMessage().c_str() ); CPPUNIT_ASSERT( false ); }catch( ... ){ CPPUNIT_ASSERT( false ); } }
void SocketTest::testAddress() { ServerSocket serv; serv.bind(SocketAddress()); serv.listen(); StreamSocket ss; ss.connect(SocketAddress("localhost", serv.address().port())); StreamSocket css = serv.acceptConnection(); assert (css.peerAddress().host() == ss.address().host()); assert (css.peerAddress().port() == ss.address().port()); }
void View::onExtractClick(wxCommandEvent &event) { if (fileInput->GetValue().Len() == 0) { wxMessageBox(wxS("You didn't specify a file."), wxS("Error"), wxOK | wxICON_ERROR, this); return; } else if (!wxFileExists(fileInput->GetValue())) { wxMessageBox(wxS("The specified file does not exist."), wxS("Error"), wxOK | wxICON_ERROR, this); return; } fileInput->Enable(false); browseButton->Enable(false); extractButton->Enable(false); // Start a server socket ServerSocket *server; try { server = ServerSocket::create(wxT("127.0.0.1"), 0); } catch (SocketException &e) { wxString message; message.Printf(wxT("Unable to start a server socket: %s"), e.getMessage().c_str()); wxMessageBox(message, wxS("Error"), wxOK | wxICON_ERROR, this); Close(); return; } // Start the disassembler. wxString command; long pid; command = wxString::Format(wxT("\"%s\" -d -M intel --remote=%d \"%s\""), findObjdump().c_str(), server->getPort(), fileInput->GetValue().c_str()); pid = wxExecute(command, wxEXEC_ASYNC, NULL); if (pid == 0) { delete server; wxMessageBox(wxS("Unable to launch the disassembler."), wxS("Error"), wxOK | wxICON_ERROR, this); Close(); return; } thread = new WorkerThread(pid, server); server->unref(); thread->Create(); thread->Run(); timer.Start(100); }
int main ( int argc, char **argv ) { std::cout << "running....\n"; //Indicate that the server is running refreshSnippets(); //refresh the snippets to make sure everything is running properly //Error handling for creating the sockets try { // Create the socket ServerSocket server (7777); while (true) { ServerSocket serverSocket; //Create the server socket server.accept (serverSocket); //Error handling for receiving the data try { while(true) { string input; //Input variable from the client serverSocket > input; //Direct the input from the socket to the variable //Check for a certain flag if(input == "-i") { // Write the reply back to the client serverSocket << "Snippet inserted"; while(1) //While true { string snippetIn; //String variable for incoming snippet serverSocket > snippetIn; //Redirect the socket data to the variable if(snippetIn == "\0") break; //Check to see if we have a terminating character writeMessage(snippetIn.c_str()); //If not, write the serialized data to a file updateDesktopFile(); //Refresh the desktop file } }; //Check for certain flags if(input == "-c") { serverSocket << "Snippets Cleared"; //Let the client know the server was cleared ofstream myfile ("snippet.txt"); //Open file without append flags myfile << "\n"; myfile.close(); // Close file updateDesktopFile(); //Update desktop file }; }// end while(true) } //Catch any exception thrown by the socket catch ( SocketException& ){} }//Close the top while(true) }// close try //Catch any exception thrown by the socket while exiting catch ( SocketException& e ) {std::cout << "Exception " << e.description() << "\n while the socket was Exiting.\n";}; return 0; }
//this thread handles socket connection to the network void * ServerThread(void * str) { printf("ServerThread Started \n"); CHKcon=0; // Create the socket ServerSocket server ( 30000 ); while(true) { ServerSocket new_sock; server.accept ( new_sock );//start listening to port 30000 try { //cvNamedWindow("thresh");/////////////delet it while (true) { ////////////ball tracking //IplImage frame0; //frame0=img0; //IplImage* imgHSV = cvCreateImage(cvGetSize(&frame0),8,3); //cvCvtColor(&frame0,imgHSV, CV_BGR2HSV); //IplImage* imgThreshed= cvCreateImage(cvGetSize(&frame0),8,1); //cvInRangeS(imgHSV,cvScalar(20,100,100),cvScalar(30,255,255),imgThreshed); //cvReleaseImage(&imgHSV); ////////////////////// std::string data; new_sock >> data; if(data.length()>2) if((data[0]=='*')&&(data[1]=='#')&&(data[data.length()-1]=='*')) { CHKcon=0;//resets connection check timer switch (data[2]) { case 'M'://Motors instruction if(data.length()==6) { //printf("%d %d \n",int(data[3])-128,int(data[4])-128); runmotors((int(data[3])-64)*4,(int(data[4])-64)*4); } break; case 'S': festivalst= data.substr(3,data.length()-4); break; } } new_sock << data; } } catch ( SocketException& ) {} usleep(1000); } }
void LocalSocketTest::testAddress() { SocketAddress sas("/tmp/poco.server.tcp.sock"); ServerSocket serv; serv.bind(sas); serv.listen(); StreamSocket ss; SocketAddress sac("/tmp/poco.client.tcp.sock"); ss.connect(sas, &sac); StreamSocket css = serv.acceptConnection(); assert (css.peerAddress().host() == ss.address().host()); assert (css.peerAddress().port() == ss.address().port()); }
int main(int argc, const char * argv[]) { ServerSocket mainSocket = ServerSocket(4444); Socket socket = mainSocket.acceptConnection(); socket.beginHandling(); socket.closeSocket(); mainSocket.close(); return 0; }
void ServerSocketTest::testGetReuseAddress() { try{ ServerSocket s; s.setReuseAddress( true ); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Reuse Address doesnt match what was set.", true, s.getReuseAddress() ); s.setReuseAddress( false ); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Reuse Address doesnt match what was set.", false, s.getReuseAddress() ); } catch( Exception& ex ) { ex.printStackTrace(); throw ex; } }
int main(int argc, char *argv[]) { QApplication app(argc, argv); ServerSocket s; ClientSocket::loadPasswd(); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); if (!s.listen(QHostAddress::Any, 4869)) { qDebug() << "cannot bind address"; exit(1); } return app.exec(); }
ServerSocket* ServerSocket::clone(struct ev_loop* loop) { ServerSocket* s = new ServerSocket(loop); s->setBacklog(backlog_); s->setReusePort(reusePort_); if (isLocal()) s->open(address_, flags_); else s->open(address_, port_, flags_); return s; }
int run() { groomLogFile(); if (runMode.compare("daemon") == 0) { dup2(ferr, 2); dup2(2, 1); } port = config["port"]; ServerSocket* ss = NULL; debug = 1; b64_hmt = base64_encode((const unsigned char*) JPEGImage::StdHuffmanTable, 420, (size_t*) & b64_hmt_l); WSServer* wss = new WSServer( config["hostName"], config["lwsDebug"], config["HTTPPort"], config["HTTPSPort"], config["sslCert"], config["sslKey"], config["sslCA"] ); try { ss = new ServerSocket(port); } catch (SocketException e) { ffl_err(FPL_MAIN, "Unable to create socket on port: %d", port); } while (ss && !force_exit && (duration == 0 || duration > (time(NULL) - starttime))) { try { ffl_notice(FPL_MAIN, "waiting for a connection on %d ...", port); FerryStream* fs = new FerryStream(ss->accept(), &ferryStreamFuneral); cleanDeadFSList(); ffl_notice(FPL_MAIN, "a connection accepted."); } catch (SocketException e) { ffl_warn(FPL_MAIN, "Exception accepting incoming connection: %s", e.description().c_str()); } catch (FerryStream::Exception e) { ffl_err(FPL_MAIN, "Exception creating a new FerryStream: %s", e.what()); } } force_exit = 1; sleep(5); cleanDeadFSList(); cleanLiveFSList(); delete ss; delete wss; terminate_all_paths(); free(b64_hmt); ffl_notice(FPL_MAIN, "BYE!"); return 0; }
/** Public thread methods (clients connect here) */ void KeyValueStore::PublicThread::run() { Thread threads[MAX_CLIENT_THREADS]; HandleClient threadInst[MAX_CLIENT_THREADS]; const Config::ServerInformation& info = config.getServerInformation(); Config::ThreadControl& control = config.getThreadControl(); int id = 0; char full = Protocol::SRV_FULL; char conn = Protocol::SRV_CONN; ServerSocket server; SocketAddress sock(info.address, info.pubPort); server.bind(sock, true); server.listen(5); printKv("Listening for clients on "<< info.address <<":"<< info.pubPort); while(control.isLive()) { // Simply do thread per client StreamSocket client = server.acceptConnection(); printKv("Received client connection request - waiting for thread to free up"); // Wait five seconds try { freeThreads.wait(5000); // This beats busy waiting } catch(TimeoutException& notUsed(e)) { printKv("Server full - closing connection to client"); client.sendBytes(&full, sizeof(full)); client.close(); continue; } // Send success client.sendBytes(&conn, sizeof(conn)); // tryJoin() doesn't work properly in linux, using isRunning() instead // actively search for the next available thread while(threads[id].isRunning()){ // Try to get an available thread id = (id + 1) % MAX_CLIENT_THREADS; Thread::sleep(250); // 250ms between each check } printKv("Serving client"); threadInst[id] = HandleClient(client, control); threads[id].start(threadInst[id]); } server.close(); freeThreads.set(); // Free a thread with semaphore }
void Communication() { try { // Create the socket ServerSocket server (port); int rounds = 16; string rStr = ""; while ( true ) { //ServerSocket new_sock; server.accept (new_sock); stop = false; weFinish = false; try { while ( true ) { std::string data; cout << "Waiting for command..." << endl; new_sock >> data; cout << "Received :: " << data << endl; if(data != "Stop") { rounds = std::stoi(data); std::thread (ExecuteThreads_high, rounds).detach(); std::thread (checkFinish).detach(); cout << "Started Computing..." << endl; } else { cout << "Stopped... Check at other server for answer" << endl; stop = true; break; } } } catch ( SocketException& e) { //cout << e.description()<< endl; } cout << "------------ Completed Successfully ---------------\n"; } } catch ( SocketException& e ) { cout << "Exception was caught:" << e.description() << "\nExiting.\n"; } }
/* * 起一个监听端口。 * * @param spec: 格式 [upd|tcp]:ip:port * @param streamer: 数据包的双向流,用packet创建,解包,组包。 * @param serverAdapter: 用在服务器端,当Connection初始化及Channel创建时回调时用 * @return IO组件一个对象的指针 */ IOComponent *Transport::listen (const char *spec, IPacketStreamer *streamer, IServerAdapter *serverAdapter, int timeout) { MutexGuard guard(&_stopMutex); if (_stop) { ANET_LOG(SPAM, "Transport(%p) Stoped!", this); return NULL; } if (NULL == spec || NULL == streamer || NULL == serverAdapter) { ANET_LOG(WARN, "Invalid parameters for listen(%p,%p,%p)", spec, streamer, serverAdapter); return NULL; } char tmp[512]; char *args[32]; strncpy(tmp, spec, 512); tmp[511] = '\0'; if (parseAddr(tmp, args, 32) != 3) { return NULL; } if (strcasecmp(args[0], "tcp") == 0) { char *host = args[1]; int port = atoi(args[2]); // Server Socket ServerSocket *socket = new ServerSocket(); assert(socket); if (!socket->setAddress(host, port)) { delete socket; return NULL; } // TCPAcceptor TCPAcceptor *acceptor = new TCPAcceptor(this, socket, streamer, serverAdapter, timeout); assert(acceptor); if (!acceptor->init()) { delete acceptor; return NULL; } // 返回 return acceptor; } else if (strcasecmp(args[0], "udp") == 0) {} return NULL; }
int64_t readAtMost(ServerSocket &s, char *buf, int64_t max, int64_t atMost) { const int64_t target = atMost < max ? atMost : max; VLOG(3) << "readAtMost target " << target; // because we want to process data as soon as it arrives, tryFull option for // read is false int64_t n = s.read(buf, target, false); if (n < 0) { PLOG(ERROR) << "Read error on " << s.getPort() << " with target " << target; return n; } if (n == 0) { LOG(WARNING) << "Eof on " << s.getFd(); return n; } VLOG(3) << "readAtMost " << n << " / " << atMost << " from " << s.getFd(); return n; }