Answer the question
In order to leave comments, you need to log in
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;
}
}
char msg[256];
int iRez;
do {
iRez = recv(Connection, msg, sizeof(msg), NULL);
cout << msg << endl;
} while (iRez > 0);
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);
recv(Connection, msg, sizeof(msg), NULL);
cout << msg;
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question