Skip to content
Snippets Groups Projects
Commit 24d72c55 authored by Ramiro Facundo Lorenzo Rodriguez Inthamoussu's avatar Ramiro Facundo Lorenzo Rodriguez Inthamoussu
Browse files

merge con remotes/origin/single-file-Y-manejo-errores a master

parents a8dc6902 6fc503cf
No related branches found
No related tags found
No related merge requests found
#ifndef CLIENTS_H_
#define CLIENTS_H_
#define UDP_PORT 9998
#define TCP_PORT 9999
int printFrame(int received_data_size, char* recibido, int fin, char* buf);
void TCP(const char* HOST);
void UDP(char* HOSTNAME);
#endif /* CLIENTS_H_ */
/*
#include <opencv2/opencv.hpp>
using namespace cv;
#include <iostream>
#include <unistd.h>
#include <stdio.h>
using namespace std;
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUFLEN 1048576 //1024*1024 //Max length of buffer
#define MAX_QUEUE 10
#define PORT 8890 //The port on which to listen for incoming data
int pruebaRecibirUDP();
int pruebaRecibirTCP();
int findPosDelimiter(const char *array, int len, char * delimiter, int inicio);
void die(char *s)
{
perror(s);
exit(1);
}
int mainOld(int argc, char *argv[]){
pruebaRecibirTCP();
}
int pruebaRecibirTCP() {
char buf[BUFLEN];
//primitiva SOCKET
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
//primitiva BIND
struct sockaddr_in server_addr;
socklen_t server_addr_size = sizeof server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(
server_socket,
(struct sockaddr*)&server_addr, server_addr_size
);
cout << "Waiting for connection..." << endl;
//primitiva LISTEN
listen(server_socket, MAX_QUEUE);
//primitiva ACCEPT
struct sockaddr_in client_addr;
socklen_t client_addr_size = sizeof client_addr;
int socket_to_client = accept(
server_socket,
(struct sockaddr *)&client_addr, &client_addr_size
);
char delimiter[] = "Grupo25";
char recibido[BUFLEN];
int fin = 0; // Mantiene el indice de los bytes recibidos.
int received_data_size = 1;
while(received_data_size > 0)
{
//primitiva RECEIVE
int data_size = BUFLEN;
received_data_size = recv(socket_to_client, buf, data_size, 0);
//print details of the client/peer and the data received
//printf("\nReceived packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
cout << "Datos recibidos: " << received_data_size << endl;
// en el arrray recibido se mantiene los datos que ya exisitian mas los nuevos.
for(int j = 0; j < received_data_size; j++) {
recibido[fin+j] = buf[j];
}
fin = fin + received_data_size;
//cout << "fin: " << fin << endl;
int inicio = 0;
int found = -1;
while ((found = findPosDelimiter(recibido, fin+1, delimiter, inicio)) != -1) {
char jpg[found-inicio];
//cout << "encontre delimitador en pos: " << found << endl;
for (int h = 0; h < found-inicio; h++) {
jpg[h] = recibido[inicio+h];
}
cout << "nuevo jpg size: " << sizeof(jpg) << endl;
namedWindow("cliente", CV_WINDOW_AUTOSIZE);
Mat rawData = Mat(1, found, CV_8UC1, jpg);
Mat frame = imdecode(rawData, CV_LOAD_IMAGE_COLOR);
imshow("cliente", frame);
waitKey(1000/30);
inicio = found + sizeof(delimiter)-1;
}
if (inicio != 0) {
// mueve los datos recibidos al inicio, quitando el (o los) frame dibujado y el delimitador
for (int d = inicio; d < fin+1; d++) {
recibido[d-inicio] = recibido[d];
}
fin = fin-inicio;
//cout << "nuevo fin: " << fin << endl;
}
}
//primitiva CLOSE
//close(socket_to_client);
close(server_socket);
return 0;
}
int findPosDelimiter(const char *array, int len, char * delimiter, int inicio) {
int i = -1;
int pos = 0;
for (i = inicio; i<len; i++) {
if (sizeof(delimiter)-1 == pos) {
if (array[i] == delimiter[pos]) {
return i - sizeof(delimiter) + 2;
} else {
pos=0;
}
} else {
if (array[i] == delimiter[pos]) {
pos++;
} else {
pos=0;
}
}
}
return -1;
}
int pruebaRecibirUDP(){
struct sockaddr_in si_me, si_other;
int s, slen = sizeof(si_other) , recv_len;
char buf[BUFLEN];
//create a UDP socket
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
die("socket");
}
// zero out the structure
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
//bind socket to port
if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)
{
die("bind");
}
socklen_t server_addr_size = sizeof si_other;
//keep listening for data
while(1)
{
printf("Waiting for data...");
fflush(stdout);
//try to receive some data, this is a blocking call
if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &server_addr_size)) == -1)
{
die("recvfrom()");
}
//print details of the client/peer and the data received
printf("\nReceived packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("Tamanio Data: %d\n", sizeof(buf));
namedWindow("cliente", CV_WINDOW_AUTOSIZE);
Mat rawData = Mat(1, sizeof(buf), CV_8UC1, buf);
Mat frame = imdecode(rawData, CV_LOAD_IMAGE_COLOR);
imshow("cliente", frame);
waitKey(1000/30);
//now reply the client with the same data
//if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1)
//{
// die("sendto()");
//}
}
close(s);
return 0;
}
*/
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <sys/socket.h> #include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h> #include <netinet/in.h>
#include "Clients.h" #include <opencv2/core/core.hpp>
#include "Util.h" #include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstdio>
#define UDP_PORT 9998
#define TCP_PORT 9999
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define MAXLEN 1048576 //1024*1024
using namespace cv;
const char delimiter[] = "Grupo25";
const int keepAliveIntervalSeconds = 30;
// DEFINICION DE FUNCIONES
int printFrame(int received_data_size, char* recibido, int fin, char* buf);
void TCP(const char* HOST);
void UDP(char* HOSTNAME);
int sendDatagramUDPtoHostname(int socket, char* HOSTNAME, char* buffer, unsigned short int destinationPort);
const char* getIP(char* hostname);
void error(const char *);
void* keepAliveMethod(void* ptr);
struct keepAliveData{
int keepAliveId;
int socketId;
char* ip;
};
/**
* Funcion auxiliar que retorna dentro del array indicando la posicion del comienzo del delimitador
* array: arreglo a consultar
* len: largo de array
* delimiter: delimitador a buscar
* inicio: desde que posicion arrancar a buscar
*/
int findPosDelimiter(const char *array, int len, int inicio) {
int i = -1;
int pos = 0;
for (i = inicio; i<len; i++){
if (sizeof(delimiter)-1 == pos)
if (array[i] == delimiter[pos])
return i - sizeof(delimiter) + 2;
else
pos=0;
else
if (array[i] == delimiter[pos])
pos++;
else
pos=0;
}
return -1;
}
void TCP(const char* HOST){
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
//obtenemos la direccion con getaddrinfo
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(HOST, STR(TCP_PORT), &hints, &res);
printf("Intentando conexion con %s:%d ...\n",HOST,TCP_PORT);
//primitiva CONNECT
if (connect(client_socket, res->ai_addr, res->ai_addrlen)<0){
printf("Error, imposible establecer conexion con el servidor.\n");
return;
}
//primitiva SEND
char msg[4];
sprintf(msg, "%s", "TCP");
msg[3] = '\0';
int msg_size = strlen(msg);
int sent_msg_size = send(client_socket, msg, msg_size, 0);
if (sent_msg_size == -1) {
printf("Error, imposible establecer conexion con el servidor.\n");
return;
}
printf("Conexion establecida.\n");
char buf[MAXLEN]; // se almacenan los datos TCP recibidos en cada recv
char recibido[MAXLEN]; // mantiene el historico de datos recibidos, quitando los frames ya dibujados
int fin = 0; // Mantiene el indice del array recibido.
int received_data_size = 1;
while(received_data_size > 0)
{
int data_size = MAXLEN;
received_data_size = recv(client_socket, buf, data_size, 0);
fin = printFrame( received_data_size, recibido, fin, buf);
}
close(client_socket);
freeaddrinfo(res);
}
int printFrame(int received_data_size, char* recibido, int fin, char* buf){
printf("Datos recibidos: %d\n", received_data_size);
// en el arrray 'recibido' se mantiene los datos que ya exisitian mas los nuevos.
for(int j = 0; j < received_data_size; j++)
recibido[fin+j] = buf[j];
fin += received_data_size;
int inicio = 0;
int found = -1;
while ((found = findPosDelimiter(recibido, fin+1, inicio)) != -1) {
char jpg[found-inicio];
for (int h = 0; h < found-inicio; h++)
jpg[h] = recibido[inicio+h];
printf("Nuevo jpeg size: %li\n", sizeof(jpg));
namedWindow("cliente", CV_WINDOW_AUTOSIZE);
Mat rawData = Mat(1, found, CV_8UC1, jpg);
Mat frame = imdecode(rawData, CV_LOAD_IMAGE_COLOR);
imshow("cliente", frame);
waitKey(30);
inicio = found + sizeof(delimiter)-1;
}
if (inicio != 0) {
// mueve los datos recibidos al inicio, quitando el (o los) frame dibujado y el delimitador
for (int d = inicio; d < fin+1; d++)
recibido[d-inicio] = recibido[d];
fin -= inicio;
}
return fin;
}
void UDP(char* HOSTNAME){
unsigned int length;
struct from;
// CREATE SOCKET
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) error("error when creating socket");
char buffer[256];
bzero(buffer,256);
sprintf(buffer, "subscription");
// ENVIO PEDIDO DE SUSCRIPCION
printf("Enviando Suscripcion a %s:%d ...\n", HOSTNAME, UDP_PORT); ::fflush(stdout);
if (sendDatagramUDPtoHostname(sock, HOSTNAME, buffer, UDP_PORT) < 0)
error("Error on send first datagram");
// ESPERO RESPUESTA DEL SERVIDOR
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
bzero(buffer,256);
struct sockaddr_in from;
if (recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length) < 0){
if ((errno == EAGAIN) || (errno == EWOULDBLOCK)){
printf("Error, no hay respuesta del servidor.\n");
return;
}else{
printf("Error al recibir datos.\n");
return;
}
}else
printf("Listo");
printf("Subscription: %s\n", buffer);
char* keepAliveId = new char[3];
keepAliveId[0] = buffer[9];
keepAliveId[1] = buffer[10];
keepAliveId[2] = '\0';
printf("keepAliveId is : %s\n", keepAliveId);
keepAliveData* kaData = new (keepAliveData);
kaData->keepAliveId = atoi(keepAliveId);
kaData->socketId = sock;
kaData->ip = new char[strlen(HOSTNAME)+1];
sprintf(kaData->ip, "%s" , HOSTNAME);
(kaData->ip)[strlen(HOSTNAME)] = '\0';
pthread_t* hilos = new pthread_t[1];
pthread_create ( &hilos[0], NULL, keepAliveMethod, (void *)kaData );
char buf[MAXLEN]; // se almacenan los datos TCP recibidos en cada recv
char recibido[MAXLEN]; // mantiene el historico de datos recibidos, quitando los frames ya dibujados
int fin = 0; // Mantiene el indice del array recibido.
int received_data_size = 1;
while(true)
{
received_data_size = recvfrom( sock , buf , MAXLEN , 0 , (struct sockaddr *)&from , &length );
if (received_data_size < 1){
if ((received_data_size < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK))){
printf("Error, no hay respuesta del servidor.\n");
return;
}else{
printf("Error al recibir datos.\n");
return;
}
}else
fin = printFrame( received_data_size, recibido, fin, buf);
}
//while (true)
//{
// memset ( frameBuffer , '\0' , 100 );
// if ( recvfrom( sock , frameBuffer , 100 , 0 , (struct sockaddr *)&from , &length ) < 0)
// error("recv from UDP frames");
// printf("%s\n", frameBuffer);
//}
close(sock);
}
void* keepAliveMethod(void* ptr){
keepAliveData* kaData = (keepAliveData*)ptr;
char* buffer = new char[13];
sprintf(buffer, "KEEPALIVE:%d", kaData->keepAliveId);
buffer[13] = '\0';
while (1){
sleep(keepAliveIntervalSeconds);
printf("Sending keep alive request :%d\n", kaData->keepAliveId );
sendDatagramUDPtoHostname(kaData->socketId, kaData->ip, buffer, UDP_PORT);
}
}
int sendDatagramUDPtoHostname(int socket, char* HOSTNAME, char* buffer, unsigned short int destinationPort){
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(getIP(HOSTNAME));
server.sin_port = htons(destinationPort);
return sendto( socket , buffer , strlen(buffer) , 0, (const struct sockaddr *)&server , sizeof(struct sockaddr_in) );
}
void error(const char *msg)
{
perror(msg);
exit(0);
}
const char* getIP(char* hostname){
struct hostent *hp = gethostbyname(hostname);
if (hp==0)
error("Unknown host");
char* ipAddress = NULL;
struct in_addr **addr_list = (struct in_addr **)hp->h_addr_list;
if(addr_list[0] != NULL){
int tam = strlen(inet_ntoa(*addr_list[0]));
ipAddress = new char[tam+1];
sprintf(ipAddress, "%s", inet_ntoa(*addr_list[0]));
ipAddress[tam] = '\0';
}else{
error("Unknown host");
}
return ipAddress;
}
......
#include "Util.h"
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
int sendDatagramUDPtoHostname(int socket, char* HOSTNAME, char* buffer, unsigned short int destinationPort){
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(getIP(HOSTNAME));
server.sin_port = htons(destinationPort);
return sendto( socket , buffer , strlen(buffer) , 0, (const struct sockaddr *)&server , sizeof(struct sockaddr_in) );
}
void error(const char *msg)
{
perror(msg);
exit(0);
}
const char* getIP(char* hostname){
struct hostent *hp = gethostbyname(hostname);
if (hp==0)
error("Unknown host");
char* ipAddress = NULL;
struct in_addr **addr_list = (struct in_addr **)hp->h_addr_list;
if(addr_list[0] != NULL){
int tam = strlen(inet_ntoa(*addr_list[0]));
ipAddress = new char[tam+1];
sprintf(ipAddress, "%s", inet_ntoa(*addr_list[0]));
ipAddress[tam] = '\0';
}else{
error("Unknown host");
}
return ipAddress;
}
#ifndef UTIL_H_
#define UTIL_H_
int sendDatagramUDPtoHostname(int socket, char* HOSTNAME, char* buffer, unsigned short int destinationPort);
const char* getIP(char* hostname);
void error(const char *);
#endif /* UTIL_H_ */
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment