I am trying to develop a Request-Response system similar to Client-Server approach, where in Client requests for its data from the Server. The response from Server is read from a file in binary and sent to respective Client, and the file size is nearly 35 KB
consisting of 120 lines.
The prototype of the file is like:
line-1: abcdefghijklmnopqrstuvwxyz
line-2: abcdefghijklmnopqrstuvwxyz
line-3: abcdefghijklmnopqrstuvwxyz
line-4: abcdefghijklmnopqrstuvwxyz
line-5: (FOR CLIENT-235)abcdefghijklmnopqrstuvwxyz
line-6: abcdefghijklmnopqrstuvwxyz
line-7: (FOR CLIENT-124)abcdefghijklmnopqrstuvwxyz
line-8: abcdefghijklmnopqrstuvwxyz
.
.
.
line-119: (FOR CLIENT-180)abcdefghijklmnopqrstuvwxyz
line-120: abcdefghijklmnopqrstuvwxyz
First four lines are for Server and next 116 are for Client(s). Starting from 5th, the data required for particular client will be two lines ie if request comes from CLIENT-235, Server has to save line-5 and line-6 data for future transactions in a Container and send to it. If the same client requests again, send line-5 and line-6 without reading the whole file. Similar approach for other Clients.
Can maintaining an Index
file will be easier which will index for particular line and information -Do I need a Map
?
I want to know what is the best way to accomplish this (atleast better way) using Vector
or simple structures
? Because the number of lines in the file may increase, so do I need sort of Dynamic Array?
One way is to use STL's map to achieve what you want. Since each client's response will be two lines of strings, you can create a struct containing two variables to store it. Then you can insert the struct into the map, with "CLIENT-X" as the index element. Lastly, use the index to retrieve the client's data. Below is an example:
#include <sstream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
struct data
{
string firstLine, secondLine;
data(){ }
};
int main()
{
ifstream file("input.txt");
std::map<string,data> mymap;
stringstream ss;
string index;
data buffer;
int client = 1;
if(file.is_open())
{
string server[4];
for(int i = 0; i < 4; i++) // read the first 4 lines for the server
getline(file, server[i]);
while(getline(file, buffer.firstLine))
{
getline(file, buffer.secondLine);
// define the index value for retrieval
ss.str("");
ss << "CLIENT-" << client;
// insert the client's data into the map
mymap.insert(pair<string,data>(ss.str(), buffer));
client++;
}
// retrieve the client's data
buffer = mymap["CLIENT-1"]; // example on how to access
// here you can do what you want, like sending to the client
//
file.close();
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.