I need to send files via Socket in Linux C ++, as the file may have extensive content I will need to send it to pieces. In this case, I need to create a kind of protocol to send a file (in pieces) through Sockets and be able to join again on the server side and / or the client side. Can anyone help with how to perform this task, below are the Server and Client methods, respectively, where I can send and receive text messages between the client and the server and vice versa.
// Método no Servidor, recebe e envia mensagem ao cliente.
void SocketServer::receiver()
{
int read_size = -1;
char msg_buf_recv[MAX_MSG];
char msg_buf_send[MAX_MSG];
std::string client_message;
while( (read_size = ::recv(sockClient, msg_buf_recv, sizeof(msg_buf_recv), 0)) > 0)
{
std::cout << msg_buf_recv << std::endl;
std::cout << "Servidor: ";
std::cin.getline(msg_buf_send, sizeof(msg_buf_send));
write(sockClient, msg_buf_send, sizeof(msg_buf_send));
}
if(read_size == 0)
{
std::cout << "\nClient disconnected" << std::endl;
}
else if(read_size == -1)
{
std::cerr << "Recv failed" << std::endl;
}
}
// Método cliente enviar e recebe mensagens ao servidor.
bool SocketClient::conectar()
{
char server_message[MAX_MSG];
char client_message[MAX_MSG];
if ( connect(sockClient, (struct sockaddr *)&client , sizeof(client)) < 0)
{
std::cerr << "Connect failed. Error" << std::endl;
return false;
}
std::cout << "Connectando..." << std::endl;
sleep( 1 );
system("clear");
std::cout << "Conectado ao Servidor IP: " << ipClient << std::endl;
while(1)
{
std::cout << "Marcos: ";
std::cin.getline (client_message, sizeof(client_message));
//Send some data
if( send(sockClient, client_message, sizeof(client_message), 0) < 0)
{
std::cerr << "Send failed" << std::endl;
return false;
}
std::cout << "Client message: " << client_message << std::endl;
//Receive a reply from the server
if( recv(sockClient, server_message, sizeof(server_message), 0) < 0)
{
std::cerr << "recv failed" << std::endl;
return false;
}
std::cout << "Server message: " << server_message << std::endl;
}
return true;
}