void *recv_variable(const int socketReceptor, int *tipo) { t_header header; void *buffer; int Leido; // Primero: Recibir el header para saber cuando ocupa el payload. Leido = Lee_Socket(socketReceptor, &header, sizeof(header)); if (Leido == -1) { perror("error al Lee_Socket recibe header"); exit(-1); } if (Leido < 1) { buffer = malloc(strlen(Leido_error) + 1); strcpy(buffer, Leido_error); } else { *tipo = (int) header.header_mensaje; // Segundo: Alocar memoria suficiente para el payload. buffer = malloc(header.payLoadLength); // Tercero: Recibir el payload. if (Lee_Socket(socketReceptor, buffer, header.payLoadLength) == -1) { perror("error al Lee_Socket receptor"); exit(-1); } } log_in_disk_mensajes(LOG_LEVEL_WARNING, "\t\t mensaje recivido tipo :%d contenido %s", *tipo, (char*) buffer); return buffer; }
/* Programa principal. Abre la conexión, recibe su número de cliente y * luego envía dicho número cada segundo */ main() { int sock; /* descriptor de conexión con el servidor */ int buffer; /* buffer de lectura de datos procedentes del servidor */ int error; /* error de lectura por el socket */ /* Se abre una conexión con el servidor */ sock = Abre_Conexion_Inet ("localhost", "8000"); /* Se lee el número de cliente, dato que nos da el servidor. Se escribe * dicho número en pantalla.*/ error = Lee_Socket (sock, (char *)&buffer, sizeof(int)); /* Si ha habido error de lectura lo indicamos y salimos */ if (error < 1) { printf ("Me han cerrado la conexión\n"); exit(-1); } /* Se escribe el número de cliente que nos ha enviado el servidor */ printf ("Soy cliente %d\n", buffer); /* Bucle infinito. Envia al servidor el número de cliente y espera un * segundo */ while (1) { Escribe_Socket (sock, (char *)&buffer, sizeof(int)); sleep (1); } }
/* * Lee datos del socket. Supone que se le pasa un buffer con hueco * suficiente para los datos. Devuelve el numero de bytes leidos o * 0 si se cierra fichero o -1 si hay error. */ int Lee_Socket(int fd, void *Datos, int Longitud) { int Leido = 0; /* * Comprobacion de que los parametros de entrada son correctos */ if ((fd == -1) || (Datos == NULL )|| (Longitud < 1)){ fprintf(stderr,"error en validacion (fd == -1) %d || (Datos == NULL ) || (Longitud < 1) %d \n",fd,Longitud); return -1; } if ((Leido = recv(fd, Datos, Longitud, MSG_WAITALL)) == -1) { /* * En caso de error, la variable errno nos indica el tipo * de error. * El error EINTR se produce si ha habido alguna * interrupcion del sistema antes de leer ningun dato. No * es un error realmente. * El error EGAIN significa que el socket no esta disponible * de momento, que lo intentemos dentro de un rato. * Ambos errores se tratan con una espera de 100 microsegundos * y se vuelve a intentar. * El resto de los posibles errores provocan que salgamos de * la funcion con error. */ switch (errno) { case EINTR: case EAGAIN: usleep(100); if (Lee_Socket(fd, Datos, Longitud) == -1) { break; } break; default: return -1; } } /* * Se devuelve el total de los caracteres leidos */ return Leido; }
int RecibirAngulos(ANGULOS *ang, int Socket){ Lee_Socket (Socket, (char *) ang, sizeof (ANGULOS)); }
void MyFrame::AZPCliente(wxCommandEvent& event) { wxMessageBox("Modo experimental\nSe recomienda no usar hasta otras actualizaciones","Divel Network",wxICON_WARNING|wxOK); int siono=wxMessageBox("Quieres utilizar IPv6?\nSi no se usara IPv4","Divel Network",wxICON_QUESTION|wxYES_NO); if(siono==wxNO){ char Cadena[1024]; char ip[1024]; char nombreCliente1[1024]; char nombreCliente2[1024]; wxString wxip=wxGetTextFromUser("Introduce la IP del server de Azpazeta","Divel Network","127.0.0.1"); strncpy(ip, (const char*)wxip.mb_str(wxConvUTF8), 1023); struct sockaddr_in Direccion; struct servent *Puerto; struct hostent *Host; Direccion.sin_addr.s_addr=inet_addr(ip); Direccion.sin_family = AF_INET; Direccion.sin_port = 6996; AZPServer = socket (AF_INET, SOCK_STREAM, 0); connect (AZPServer, (struct sockaddr *)&Direccion, sizeof (Direccion)); Lee_Socket(AZPServer, Cadena,1024); wxMessageBox(wxString::Format("%s",Cadena),"Server informa",wxICON_INFORMATION|wxOK); wxString onlinename=wxGetTextFromUser("Introduce tu nombre online","Divel Network",""); strncpy(nombreCliente1, (const char*)onlinename.mb_str(wxConvUTF8), 1023); Escribe_Socket(AZPServer, nombreCliente1, 1024); Lee_Socket(AZPServer, nombreCliente2, 1024); wxMessageBox(wxString::Format("El otro jugador es: %s",nombreCliente2),"Divel Network"); }else{ //IPv6 char Cadena[1024]; char ip[1024]; char nombreCliente1[1024]; char nombreCliente2[1024]; wxString wxip=wxGetTextFromUser("Introduce la IPv6 del server de Azpazeta","Divel Network","::1"); strncpy(ip, (const char*)wxip.mb_str(wxConvUTF8), 1023); struct sockaddr_in6 Direccion; struct servent *Puerto; struct hostent *Host; //Direccion.sin6_len = sizeof(Direccion); //unsigned char ipv6[16]="::1"; inet_pton(PF_INET6, ip,&(Direccion.sin6_addr)); //Direccion.sin6_addr.s6_addr=inet_pton(); //Direccion.sin6_addr.s6_addr=inet_addr6(ip); Direccion.sin6_family = AF_INET6; Direccion.sin6_port = 6996; AZPServer = socket (AF_INET6, SOCK_STREAM, 0); connect (AZPServer, (struct sockaddr *)&Direccion, sizeof (Direccion)); Lee_Socket(AZPServer, Cadena,1024); wxMessageBox(wxString::Format("%s",Cadena),"Server informa",wxICON_INFORMATION|wxOK); wxString onlinename=wxGetTextFromUser("Introduce tu nombre online","Divel Network",""); strncpy(nombreCliente1, (const char*)onlinename.mb_str(wxConvUTF8), 1023); Escribe_Socket(AZPServer, nombreCliente1, 1024); Lee_Socket(AZPServer, nombreCliente2, 1024); wxMessageBox(wxString::Format("El otro jugador es: %s",nombreCliente2),"Divel Network"); } AZPServerData datos; MyEstado myestado; datos.money=money; datos.level=level; datos.city=city; datos.name="A"; datos.droga=droga; datos.blacklist=blacklist; datos.socio=socio; datos.electro=electro; datos.food=food; datos.textil=textil; datos.sobornos=sobornos; datos.mision=mision; datos.rich=rich; write(AZPServer, &datos, sizeof(datos)); read(AZPServer, &myestado, sizeof(myestado)); if(myestado.bien==true){wxMessageBox(wxString::Format("Bien, el otro tienen menos, concretamente: %d", myestado.moneyotro));} if(myestado.bien==false){wxMessageBox(wxString::Format("Mal, el otro tiene mas, concretamente: %d", myestado.moneyotro));} //close(AZPServer); wxTimer* timer; timer=new wxTimer(this, TIMER_ID); timer->Start(60000, false); wxMessageBox(wxT("Empezando nueva partida"), wxT("Azpazeta"),wxICON_INFORMATION|wxOK); newname=wxGetTextFromUser(wxT("Introduce tu nombre para la partida"),wxT("Azpazeta"),wxT("")); wxBitmap bocadillo("/opt/extras.ubuntu.com/azpazeta/media/Bocadillo.png",wxBITMAP_TYPE_PNG); Bocadillo=new wxStaticBitmap(panel, ID_DIBUJO, bocadillo, wxPoint(600,450)); cap1mis1=new wxStaticText(panel, ID_DIBUJO, wxT(CAP1MIS1TEX1), wxPoint(625, 470)); actualizar=new wxButton(panel, wxID_ANY, "..."); jugar=new wxButton(panel, wxID_ANY, "..."); instrucciones=new wxButton(panel, wxID_ANY, "..."); city=1; Adrix->Destroy(); money=2000; mision=0; level=0; MyFrame::Stage1(); }