3
I am needing to send files via Socket on C++ Linux, as the file may have an extensive content it will need to be sent in 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 and/or client side. Does anyone can help in how to accomplish this task, follows below the Server and Client methods, respectively, where I can send and receive text messages between client and 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;
}
Very good tip and used in my application, however, I’m still doubtful to receive the file on the Server/ Client side, IE recv, how do I join the parts?
– Marcos
@Mark, I’m sorry for the delay, I was away from the computer, I made up my mind because I have no compiler in sight. I will try to update again tomorrow with a full source.
– Vitor Caleffi
Thanks, I’m waiting for the complete source, as I couldn’t understand it properly, I ended up trying to redo everything, but it’s not working. If you have everything complete the understanding will be much better and will be of great help.
– Marcos
@Marcos https://www.dropbox.com/s/k08u4ya6k0babj2/Server.rar?dl=0
– Vitor Caleffi
Thanks for the strength Vitor! I will analyze to better understand this matter.
– Marcos