I send packets of different sizes one after the other, how can I receive the packets separately at the size I send, not cumulated in the buffer. It seems that now the server adds to the buffer until it fills it and then I can process them.
Example:
Buffer size: 84.
Send from client: 84 bytes, 76 bytes, 76 bytes, 80 bytes
Receive in server: 84 bytes, 84 bytes, 84 bytes, 64 bytes.
I would like to receive them as I sent them. Is it possible?
int port = stoi(getConfig("server_port"));
std::string ipAddress = getConfig("ip_address");
// Create a socket
int listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening < 0){
std::cerr << "Can't create a socket!" << endl;
Logger("Can't create a socket!");
exit(-1);
}
std::cout << "The socket server was created successfully." << endl;
// Bind the socket to a IP / port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
if (bind(listening, (sockaddr*)&hint, sizeof(hint)) < 0){
cerr << "Can't bind to IP/port!" << endl;
Logger("Can't bind to IP/port!");
exit(-1);
}
// Mark the socket for listening in
if (listen(listening, SOMAXCONN) < 0){
cerr << "Can't listen!" << endl;
Logger("Can't listen!");
exit(-1);
}
// Accept a call
sockaddr_in client;
socklen_t clientSize = sizeof(client);
char host[NI_MAXHOST];
char svc[NI_MAXSERV];
while(true){
int clientSoket = accept(listening, (sockaddr*)&client, &clientSize);
if(clientSoket < 0){
cerr << "Problem with client connecting!" << endl;
Logger("Problem with client connecting!");
break;
}
cout << "The client whas conected successfully." << endl;
memset(host, 0, NI_MAXHOST);
memset(svc, 0, NI_MAXSERV);
int result = getnameinfo((sockaddr*)&client, clientSize, host, NI_MAXHOST, svc, NI_MAXSERV, 0);
if(result == 0) {
cout << host << " connected on " << svc << endl;
} else {
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on " << ntohs(client.sin_port) << endl;
}
// While receiving
char buff[84];
while(true){
// Clear the buffer
memset(buff, 0, sizeof(buff));
// Wait for a message
int bytesRecv = recv(clientSoket, buff, sizeof(buff), 0);
if(bytesRecv < 0){
cerr << "There was a connection issue!" << endl;
Logger("There was a connection issue!");
break;
}
if(bytesRecv == 0){
cout << "The client disconnected." << endl;
Logger("The client disconnected");
break;
}
cout << "bytesRecv: " << bytesRecv << endl;
}
// Close the socket
close(clientSoket);
}