E
E
enotiik2021-12-07 19:03:38
C++ / C#
enotiik, 2021-12-07 19:03:38

How to transfer data through sockets?

We study network programming in C++ at the university. They set the laboratory, with it there were problems. The server program generates a matrix of integer random numbers, the client program receives the matrix and displays it.

The first solution was this.

Server code:

for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            string buf = to_string(rand() % 100);
            const char* msg = buf.c_str();
            send(newConnection, msg, sizeof(msg), NULL);
            cout << msg << endl;
        }
    }


Client code:
char msg[256];
    int iRez;
    do {
        iRez = recv(Connection, msg, sizeof(msg), NULL);
        cout << msg << endl;
    } while (iRez > 0);

The problem here is that some numbers are lost.
Screenshot with results
61af839f0cd8b123726280.png

While writing the question, not so much was lost, but before that, more than half were not.

There is also a second solution. In it, I pack all the numbers and separators (\t and \n) into one line and send it.

Server code:
string msg="";
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            msg = msg + to_string(rand() % 100) + "\t";
        }
        msg += "\n";
    }
    const char* c_msg = msg.c_str();
    cout << c_msg << endl;
    send(newConnection, c_msg, sizeof(c_msg), NULL);


Client code:
recv(Connection, msg, sizeof(msg), NULL);
    cout << msg;

The result is:
Screenshot with results
61af84ed5e929935799785.png

How to pass/receive a matrix correctly? If there is intelligible literature or sites on the topic, I will be grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
none7, 2021-12-07
@enotiik

send and recv are binary data functions. For them, the correct length is very important.
send(newConnection, msg, sizeof(msg), NULL); sizeof is a pure C construct. In this case, it returns 4 or 8, depending on the program's machine code architecture. That is the size of the pointer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question