Code:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#define PUERTO 25500
bool establecer_socket(int &sock, sockaddr_in &dir);
int mandar(int sock, int *buf, int longitud)
{
return (send(sock, buf, longitud, MSG_NOSIGNAL));
}
int recibir(int sock, int *buf, int longitud)
{
return (recv(sock, buf, longitud, 0));
}
int main()
{
using namespace std;
int sock_handle, dimension, nueva_sock;
sockaddr_in direccion;
int i, cnt;
cnt = 0; // contador para el numero de peticiones que resuelva
// preparar a la socket para ser usada antes de bind
if(establecer_socket(sock_handle, direccion))
{
cout << "ESCUCHANDO!...\n";
}
else
{
cout << "ERROR EN LA CONEXION...";
exit(1);
}
listen(sock_handle, 5);
while(true)
{
dimension = sizeof(direccion);
nueva_sock = accept(sock_handle, (sockaddr *) &direccion, (socklen_t *) &dimension);
if(nueva_sock < 0)
{
exit(1);
}
while(recibir(nueva_sock, &i, sizeof(i)) > 0)
{
using namespace std;
cnt = cnt + 1;
i = i / 10;
cout << "\nNumero rebotado: " << i;
cout << " # de solicitud: " << cnt;
mandar(nueva_sock, &i, sizeof(i));
}
close(nueva_sock);
}
return 0;
}
bool establecer_socket(int &sock, sockaddr_in &dir)
{
bool result = true;
int opt = 1; // opciones que se pasan con setsockopt
result = ( (sock = socket(AF_INET, SOCK_STREAM, 0)) >= 0);
if(result)
{
result = ( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &opt, sizeof(opt)) == 0 );
memset(&dir, 0, sizeof(sockaddr_in));
dir.sin_family = AF_INET;
dir.sin_port = htons(25500);
dir.sin_addr.s_addr = INADDR_ANY;
}
if(result)
{
result = (bind(sock, (sockaddr *) &dir, sizeof(dir)) == 0);
}
return result;
}
Here is the server code. As I had already said, it is fairly short. Let me make the comment once again, that the client itself gets replies from the server every time. Hence I know they are communicating so the problem lies elsewhere. By the way, sorry about the Spanish, I didn't think I'd have to post the code on a forum to seek help so some of the parts are like that, though I thrust it is by no means critical.