1

クライアントがサーバーからのデータを要求する、クライアントサーバーアプローチに似た要求応答システムを開発しようとしています。サーバーからの応答はバイナリ形式のファイルから読み取られ、それぞれのクライアントに送信されます。ファイル サイズは約35 KB120 行です。

ファイルのプロトタイプは次のようになります。

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

最初の 4 行はサーバー用で、次の 116 行はクライアント用です。5 日以降、特定のクライアントに必要なデータは 2 行になります。つまり、要求が CLIENT-235 から送信された場合、サーバーは将来のトランザクションのために行 5 と行 6 のデータをコンテナに保存して送信する必要があります。同じクライアントが再度要求した場合は、ファイル全体を読み取らずに行 5 と行 6 を送信します。他のクライアントに対する同様のアプローチ。

Index特定の行と情報をインデックス化するファイルの維持がより簡単になりMapますか?

Vectorまたはシンプルを使用してこれを達成するための最良の方法(少なくともより良い方法)を知りたいstructuresですか?ファイルの行数が増える可能性があるため、一種の動的配列が必要ですか?

4

1 に答える 1

0

1 つの方法は、STL のマップを使用して目的を達成することです。各クライアントの応答は 2 行の文字列になるため、それを格納する 2 つの変数を含む構造体を作成できます。次に、インデックス要素として「CLIENT-X」を使用して、構造体をマップに挿入できます。最後に、インデックスを使用してクライアントのデータを取得します。以下に例を示します。

#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;
}   
于 2013-09-26T13:35:16.547 に答える