void TelnetServer::start( int port ) { Socket::Address addr( port ); mSocket.bind( addr ); mSocket.listen( 5 ); mSocket.setSelector( this, &mSelector ); }
void SocketTest::testConnect() { ServerSocket serv; serv.bind(SocketAddress()); serv.listen(); StreamSocket ss; Timespan timeout(250000); ss.connect(SocketAddress("localhost", serv.address().port()), timeout); }
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(); }
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 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()); }
/** 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 SocketTest::testConnectRefused() { ServerSocket serv; serv.bind(SocketAddress()); serv.listen(); Poco::UInt16 port = serv.address().port(); serv.close(); StreamSocket ss; Timespan timeout(250000); try { ss.connect(SocketAddress("localhost", port)); fail("connection refused - must throw"); } catch (ConnectionRefusedException&) { } }
void LocalSocketTest::testConnectRefusedNB() { SocketAddress sas("/tmp/poco.server.tcp.sock"); ServerSocket serv; serv.bind(sas); serv.listen(); serv.close(); StreamSocket ss; Timespan timeout(10000); SocketAddress sac("/tmp/poco.client.tcp.sock"); try { ss.connect(sas, timeout, &sac); fail("connection refused - must throw"); } catch (TimeoutException&) { } catch (ConnectionRefusedException&) { } }
TEST(Sockets, data) { ServerSocket ssck; ssck.bind(1337); NetworkAddress addr1("127.0.0.1", 1337); Socket sck1; sck1.connect(addr1); Socket* sck2 = ssck.accept(); std::string lipsum = TestHelper::getLoremIpsum(); uint8_t* data = (uint8_t*) lipsum.data(); unsigned int len = (unsigned int) lipsum.size(); SocketInputStream* s1in = sck1.getInputStream(); SocketOutputStream* s2out = sck2->getOutputStream(); s2out->write(128); ASSERT_EQ(128, s1in->read()); s2out->write(data, len); for (unsigned int i = 0; i < len; ++i) { ASSERT_EQ(data[i], s1in->read()); } s1in->close(); ASSERT_THROW(s1in->read(), SocketException); s2out->write(128); ASSERT_THROW(s2out->write(128), SocketException); //ASSERT_EQ(-1, s1in.read()); delete sck2; }
int main(int argc, char *argv[]) { LogFile log("test.log"); log << "**************************" << "New server session started"; Address addr(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(!addr.getHost(HOST, PORT)) { logHost(log, "Unable to resolve"); return 1; } else { logHost(log, "Resolved"); } ServerSocket server; if(server.bind(addr) <= 0) { logHost(log, "Unable to bind to"); return 2; } else { logHost(log, "Bound to"); } cout << "Server FD: " << server << endl; if(!server.listen(10)) { logHost(log, "Unable to listen on"); return 3; } else { logHost(log, "Listening on"); cout << "Listening on " << HOST << ":" << PORT << endl; } // Client and select poll structure setup //vector<ClientSocket> clients; map<int, unique_ptr<ClientSocket>> table; map<int, string> names; Multiplexer select; server.setNonBlock(1); select.insert(server); Galaxy galaxy; while(true) { if(select.poll() == -1) { cerr << "select.poll() error\n"; break; } for(int i = 0; i < FD_SETSIZE; ++i) { if(select.setRead(i)) { if(server == i) { ClientSocket *client = new ClientSocket(server.accept()); if(client) { client->setNonBlock(1); select.insert(*client); table[*client] = unique_ptr<ClientSocket>(client); } else log << "A client was rejected from the server"; continue; } char buf[256]; int bytes = recv(i, &buf[0], 255, 0); if(bytes <= 0) { table[i]->close(); galaxy.rmPlayer(names[i]); select.eradicate(i); continue; } buf[bytes] = '\0'; string buffer(buf); cout << "Client: " << buffer; auto pos = buffer.find(':'); if(buffer.substr(0, pos) == "Login") { string name = buffer.substr(pos + 1, buffer.size() - pos); Player *p; try { p = &galaxy.newPlayer(name); } catch(...) { table[i]->close(); select.eradicate(i); } names[i] = name; string planet = "Planet:" + to_string(p->world().x()) + ":" + to_string(p->world().y()) + "\n"; table[i]->write(planet.c_str()); } // End of client handler block } } } for(auto& client : table) { if(client.second > 0) client.second->close(); } return 0; }
void FileTransferSocketThread::execute() { if(info.hostType == eServer) { ServerSocket serverSocket; serverSocket.bind(this->info.serverPort); serverSocket.listen(1); Socket *clientSocket = serverSocket.accept(); char data[513]=""; memset(data, 0, 256); clientSocket->receive(data,256, true); if(*data == SEND_FILE) { FileInfo file; memcpy(&file, data+1, sizeof(file)); *data=ACK; clientSocket->send(data,256); Checksum checksum; checksum.addFile(file.fileName); file.filecrc = checksum.getSum(); ifstream infile(file.fileName.c_str(), ios::in | ios::binary | ios::ate); if(infile.is_open() == true) { file.filesize = infile.tellg(); infile.seekg (0, ios::beg); memset(data, 0, 256); *data=SEND_FILE; memcpy(data+1,&file,sizeof(file)); clientSocket->send(data,256); clientSocket->receive(data,256, true); if(*data != ACK) { //transfer error } int remain=file.filesize % 512 ; int packs=(file.filesize-remain)/512; while(packs--) { infile.read(data,512); //if(!ReadFile(file,data,512,&read,NULL)) // ; //read error //if(written!=pack) // ; //read error clientSocket->send(data,512); clientSocket->receive(data,256, true); if(*data!=ACK) { //transfer error } } infile.read(data,remain); //if(!ReadFile(file,data,remain,&read,NULL)) // ; //read error //if(written!=pack) // ; //read error clientSocket->send(data,remain); clientSocket->receive(data,256, true); if(*data!=ACK) { //transfer error } infile.close(); } } delete clientSocket; } else { Ip ip(this->info.serverIP); ClientSocket clientSocket; clientSocket.connect(this->info.serverIP, this->info.serverPort); if(clientSocket.isConnected() == true) { FileInfo file; file.fileName = this->info.fileName; //file.filesize = //file.filecrc = this->info. string path = extractDirectoryPathFromFile(file.fileName); createDirectoryPaths(path); ofstream outFile(file.fileName.c_str(), ios_base::binary | ios_base::out); if(outFile.is_open() == true) { char data[513]=""; memset(data, 0, 256); *data=SEND_FILE; memcpy(data+1,&file,sizeof(file)); clientSocket.send(data,256); clientSocket.receive(data,256, true); if(*data!=ACK) { //transfer error } clientSocket.receive(data,256,true); if(*data == SEND_FILE) { memcpy(&file, data+1, sizeof(file)); *data=ACK; clientSocket.send(data,256); int remain = file.filesize % 512 ; int packs = (file.filesize-remain) / 512; while(packs--) { clientSocket.receive(data,512,true); outFile.write(data, 512); if(outFile.bad()) { //int ii = 0; } //if(!WriteFile(file,data,512,&written,NULL)) // ; //write error //if(written != pack) // ; //write error *data=ACK; clientSocket.send(data,256); } clientSocket.receive(data,remain,true); outFile.write(data, remain); if(outFile.bad()) { //int ii = 0; } //if(!WriteFile(file,data,remain,&written,NULL)) // ; //write error //if(written!=pack) // ; //write error *data=ACK; clientSocket.send(data,256); Checksum checksum; checksum.addFile(file.fileName); uint32 crc = checksum.getSum(); if(file.filecrc != crc) { //int ii = 0; } //if(calc_crc(file)!=info.crc) // ; //transfeer error } outFile.close(); } } } }