Mark Slee | e854063 | 2006-05-30 09:24:40 +0000 | [diff] [blame] | 1 | #include "server/TSimpleServer.h" |
| 2 | #include <string> |
| 3 | using namespace std; |
| 4 | |
| 5 | void TSimpleServer::run() { |
| 6 | TTransport* client; |
| 7 | |
| 8 | // Start the server listening |
| 9 | if (serverTransport_->listen() == false) { |
| 10 | // TODO(mcslee): Log error here |
| 11 | fprintf(stderr, "TSimpleServer::run(): Call to listen failed\n"); |
| 12 | return; |
| 13 | } |
| 14 | |
| 15 | // Fetch client from server |
| 16 | while (true) { |
| 17 | // fprintf(stderr, "Listening for connection\n"); |
| 18 | if ((client = serverTransport_->accept()) == NULL) { |
| 19 | // fprintf(stderr, "Got NULL connection, exiting.\n"); |
| 20 | break; |
| 21 | } |
| 22 | |
| 23 | while (true) { |
| 24 | // Read header from client |
| 25 | // fprintf(stderr, "Reading 4 byte header from client.\n"); |
| 26 | string in; |
| 27 | if (client->read(in, 4) <= 0) { |
| 28 | // fprintf(stderr, "Size header negative. Exception!\n"); |
| 29 | break; |
| 30 | } |
| 31 | |
| 32 | // Read payload from client |
| 33 | int32_t size = *(int32_t*)(in.data()); |
| 34 | // fprintf(stderr, "Reading %d byte payload from client.\n", size); |
| 35 | if (client->read(in, size) < size) { |
| 36 | // fprintf(stderr, "Didn't get enough data!!!\n"); |
| 37 | break; |
| 38 | } |
| 39 | |
| 40 | // Pass payload to dispatcher |
| 41 | // TODO(mcslee): Wrap this in try/catch and return exceptions |
| 42 | string out = dispatcher_->dispatch(in); |
| 43 | |
| 44 | size = out.size(); |
| 45 | |
| 46 | // Write size of response packet |
| 47 | client->write(string((char*)&size, 4)); |
| 48 | |
| 49 | // Write response payload |
| 50 | client->write(out); |
| 51 | } |
| 52 | |
| 53 | // Clean up that client |
| 54 | // fprintf(stderr, "Closing and cleaning up client\n"); |
| 55 | client->close(); |
| 56 | delete client; |
| 57 | } |
| 58 | |
| 59 | // TODO(mcslee): Is this a timeout case or the real thing? |
| 60 | } |