Concurrent TCP client/server


 
Thread Tools Search this Thread
Top Forums Programming Concurrent TCP client/server
# 1  
Old 02-13-2010
Concurrent TCP client/server

I made a program and now I need to make it concurrent.
Can someone pls help me do this ?

The code is this:

Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>


/* portul folosit */
#define PORT 4256

struct operation
{
    int number1;
    int number2;
    int number3;
    int number4;
    int number5;
};

/* codul de eroare returnat de anumite apeluri */
extern int errno;

/* programul */
int main (int argc, char * argv[])
{
  struct sockaddr_in server;    /* structurile folosite de server si client */
  struct sockaddr_in from;
  struct operation request;    /* cererea primita de server */
  int sd;            /* descriptorul de socket */
  int port;
  
  /* setare port in cazul specificarii explicite */
  if (argc > 1)
  {
    port = atoi(argv[1]);
  }
  else
    port = PORT;

  /* cream un socket */
  if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      perror ("Eroare la socket().\n");
      return errno;
    }

  /* pregatim structurile de date */
  bzero (&server, sizeof (server));
  bzero (&from, sizeof (from));
  
  /* umplem structura folosita de server */
  server.sin_family = AF_INET;    
      /* stabilirea familiei de socket-uri */
  server.sin_addr.s_addr = htonl (INADDR_ANY);
      /* acceptam orice adresa */
  server.sin_port = htons (port);
      /* utilizam un port utilizator */

  /* atasam socketul */
  if (bind (sd, (struct sockaddr *) &server, sizeof (struct sockaddr)) == -1)
    {
      perror ("Eroare la bind().\n");
      return errno;
    }

  /* punem serverul sa asculte daca vin clienti sa se conecteze */
  if (listen (sd, 3) == -1)
    {
      perror ("Eroare la listen().\n");
      return errno;
    }

  /* servim in mod iterativ clientii... */
  while (1)
    {
      int client;
      int length = sizeof (from);

      printf ("Asteptam la portul %d...\n", port);
      fflush (stdout);

      /* acceptam un client (ne vom bloca pina la realizarea conexiunii) */
      client = accept (sd, (struct sockaddr *) &from, &length);

      /* eroare la acceptarea conexiunii de la un client */
      if (client < 0)
    {
      perror ("Eroare la accept().\n");
      continue;
    }

      /* am realizat conexiunea, asteptam mesajul... */
      bzero (&request, sizeof(struct operation));
      printf ("Asteptam cererea...\n");
      fflush (stdout);
      
      /* citirea mesajului */
      int nrbytes = recv (client, &request, sizeof(struct operation), 0);
      if (nrbytes <= 0)
    {
      perror ("Eroare la read() de la client.\n");
      close (client);    /* inchidem conexiunea cu clientul */
      continue;        /* continuam sa ascultam... */
    }

      if (nrbytes < sizeof(struct operation))
      {
        perror ("Date primite incomplet");
    close (client);
    continue;
      }

      request.number1 = ntohl(request.number1);
      request.number2 = ntohl(request.number2);
      request.number3 = ntohl(request.number3);
      request.number4 = ntohl(request.number4);
      request.number5 = ntohl(request.number5);

      printf ("Cerere primita... \n In curs de rezolvare: %d %d %d %d %d \n", 
               request.number1, request.number2, request.number3, request.number4, request.number5);
      
      /* rezolvarea cererii */

int magic;
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int min=0;
int result;


magic = rand() % 1001; /* generarea numarului magic de la 1 la 1000*/


/* diferenta dintre numarul magic si numerele primite */

if (magic >= request.number1)
a = magic - request.number1;
else
a = request.number1 - magic;

if (magic >= request.number2)
b = magic - request.number2;
else
b = request.number2 - magic;

if (magic >= request.number3)
c = magic - request.number3;
else
c = request.number3 - magic;

if (magic >= request.number4)
d = magic - request.number4;
else
d = request.number4 - magic;

if (magic >= request.number5)
e = magic - request.number5;
else
e = request.number5 - magic;

printf("\nnumar magic: %d\n", magic);
printf("numerele sunt: %d %d %d %d %d\n", a, b, c, d, e);
/* verificare care numar este mai aproape de numarul magic */

if (a > b)
min = b;
else min = a;

if (min > c)
min = c;

if (min > d)
min = d;

if (min > e)
{
min = e;
//result = min;
}
    printf("diferenta minima este: %d", min);
    /*selectam numarul care este mai apropiat de numarul magic*/
    if (min == a)
        result = request.number1;
    if (min == b)
        result = request.number2;
    if (min == c)
        result = request.number3;
    if (min == d)
        result = request.number4;
    else
        result = request.number5;
        
      result = htonl(result);

      /* returnam rapunsul clientului */
      if (send (client, &result, sizeof(int),0) <= 0)
    {
      perror ("Eroare la write() catre client.\n");
      continue;        /* continuam sa ascultam */
    }
      else
    printf (" trasmitere cu succes.\n");
      /* am terminat cu acest client, inchidem conexiunea */
      close (client);
    }                /* while */
}                /* main */

The program is a client/server. The server generates a random number and the clients(maximum 3) have to guess that number. The sever will only take the first 5 numbers from every client and see wich one is closest. The one that guesses the number or is the clossest will get a message that will say that he guessed the number!

Can someone pls help me make my server to be concurrent and to send messages to the one that is the closest ?

Now my program only gets the 5 numbers from the client, checks wich number is closest to the random number(the magic number) and returns that number to the client!

I tried to change it and use the fork() function but i got stuck because i got lots of errors and didn't knew how to resolve them!
# 2  
Old 02-13-2010
Hello,

You need to fork a child process everytime the server accepts new requests.

Code:
int sockfd, newsockfd;

if( (sockfd=socket(...)) < 0)
       err_sys("socket error");
if(bind(sockfd,...)<0)
       err_sys("bind error");
if(listen(sockfd,3)<0)
       err_sys("listen error");

while(1){
newsockfd=accept(sockfd,....);
if(newsockfd < 0){
err_sys("accept error");

if(fork() ==0){
close(sockfd);      // child process
do_the_request(newsockfd);  //put your processing work here
exit(0);
}

close(newsockfd);    //parent

}

Regards,
Gaurav.
# 3  
Old 02-14-2010
I have modified a little my code but it doesn't seem to work Smilie

Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <errno.h>
#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>

const int PORT_SERVER = 6440; 			/* portul folosit */
const int CLIENTI_MAXIM = 3;			/* nr maxim de clienti acceptati */

extern int errno; 						/* eroare returnata */
int nr = 0;								/* numar de clienti */
int port;								/* portul*/
struct operation request;			   	/* cererea primita de server */
int sockfd, newsockfd, frlen, servlen;

struct operation
{
    int number1;
    int number2;
    int number3;
    int number4;
    int number5;
};

/*functie de tratare a semnalelor*/
void semnal (int nr_semnal) 
{
	if (nr_semnal == SIGCHLD)
	{
		wait(NULL);
		nr--; /*s-a pierdut un client*/
		return;
	}
}

/*operatiile pentru fiecare client*/
void doprocessing(int sock)
{
	printf("Esti clientul cu numarul: %d !\n", nr+1); 
	 
	/* am realizat conexiunea, asteptam mesajul... */
	bzero (&request, sizeof(struct operation));
	printf ("Asteptam cererea...\n");
	fflush (stdout);
      
	/* citirea mesajului */
	int nrbytes = recv (newsockfd, &request, sizeof(struct operation), 0);
	
	/*incercam sa citim datele de la client*/
	if (nrbytes <= 0)
    {
		perror ("Eroare la read() de la client.\n");
		close (newsockfd);    /* inchidem conexiunea cu clientul */
	}
	
	/*verificam integritatea datelor*/
	if (nrbytes < sizeof(struct operation))
    {
		perror ("Date primite incomplet");
		close (newsockfd);
    }
	
	request.number1 = ntohl(request.number1);
    request.number2 = ntohl(request.number2);
    request.number3 = ntohl(request.number3);
    request.number4 = ntohl(request.number4);
	request.number5 = ntohl(request.number5);

	printf ("Cerere primita... \n In curs de rezolvare: %d %d %d %d %d \n", 
											request.number1, request.number2, request.number3, request.number4, request.number5);
      
      
	/* rezolvarea cererii */

	int magic;
	int a=0;
	int b=0;
	int c=0;
	int d=0;
	int e=0;
	int min=0;
	int result;

	/* generarea numarului magic de la 1 la 1000*/
	magic = rand() % 1001; 

	/* diferenta dintre numarul magic si numerele primite */
	if (magic >= request.number1)
		a = magic - request.number1;
	else
		a = request.number1 - magic;

	if (magic >= request.number2)
		b = magic - request.number2;
	else
		b = request.number2 - magic;

	if (magic >= request.number3)
		c = magic - request.number3;
	else
		c = request.number3 - magic;

	if (magic >= request.number4)
		d = magic - request.number4;
	else
		d = request.number4 - magic;

	if (magic >= request.number5)
		e = magic - request.number5;
	else
		e = request.number5 - magic;

	printf("\nnumar magic: %d\n", magic);
	printf("numerele sunt: %d %d %d %d %d\n", a, b, c, d, e);
	
	/* verificare care numar este mai aproape de numarul magic */
	if (a > b)
		min = b;
	else 
		min = a;

	if (min > c)
		min = c;

	if (min > d)
		min = d;

	if (min > e)
	{
		min = e;
		//result = min;
	}
	printf("diferenta minima este: %d", min);
	
	/*selectam numarul care este mai apropiat de numarul magic*/
	if (min == a)
		result = request.number1;
	if (min == b)
		result = request.number2;
	if (min == c)
		result = request.number3;
	if (min == d)
		result = request.number4;
	else
		result = request.number5;
		
    result = htonl(result);
	/* returnam rapunsul clientului */
    if (send (newsockfd, &result, sizeof(int),0) <= 0)
    {
		perror ("Eroare la write() catre client.\n");
    }
    else
		printf ("\nTrasmitere cu succes.\n");
      /* am terminat cu acest client, inchidem conexiunea */
      close (newsockfd);
}

/*programul principal*/
int main (int argc, char * argv[])
{
	struct sockaddr_in server , from;    	/* structurile folosite de server si client */
	int port;								/* portul */
	pid_t pid;								/* Process ID from fork() */

	
	/* setare port in cazul specificarii explicite */
	if (argc > 1)
	{
		port = atoi(argv[1]);
	}
	else
		port = PORT_SERVER;
	
	/*tratarea semnalele*/
	if (signal (SIGCHLD, semnal) == SIG_ERR)
	{
		perror("signal()");
		exit(errno);
	}
	
	/* cream un socket */
	sockfd = socket(AF_INET, SOCK_STREAM,0);
	if (sockfd <0)
	{
		perror("Eroare la socket().");
		exit(1);
	}
	
	frlen = sizeof (from);
	servlen = sizeof (server);
	
	/* pregatim structurile de date */
	bzero (&server, servlen);
	bzero (&from, frlen);
  
	/* umplem structura folosita de server */
	server.sin_family = AF_INET;    					/* stabilirea familiei de socket-uri */
	server.sin_addr.s_addr = htonl (INADDR_ANY);		/* acceptam orice adresa */
	server.sin_port = htons (port);						/* utilizam un port utilizator */
	
	/* atasam socketul */
	if (bind (sockfd, (struct sockaddr *) &server, servlen) == -1)
    {
		perror ("Eroare la bind().\n");
		exit(1);
    }
	
	/* punem serverul sa asculte daca vin clienti sa se conecteze */
	if (listen (sockfd, 3) == -1)
    {
		perror ("Eroare la listen().\n");
		exit(1);
    }
	
	/*servim in mod concurent clientii*/
	while (1) 
    {
		printf ("Asteptam la portul %d...\n", port);
		fflush (stdout);
	
        newsockfd = accept(sockfd, (struct sockaddr *) &from, &frlen);
        if (newsockfd < 0)
        {
            perror("Eroare la accept().\n");
            exit(1);
        }
		
		/* Verificam daca am ajuns la numarul maxim de clienti */
		if (nr == CLIENTI_MAXIM)
		{
			perror("Numar maxim de clienti atins. Incercati mai tarziu.\n");
			shutdown(newsockfd,2);
			continue;
		}
		
        /* Cream procesul copil*/
        pid = fork();
        if (pid < 0)
        {
            perror("Eroare la fork().\n");
	    exit(1);
        }
        if (pid == 0)  
        {
            /* Procesul parcurs de client */
            close(sockfd);
            doprocessing(newsockfd);
            exit(0);
        }
        else
        {
            close(newsockfd);
        }
		nr++;
    }
}

I managed to make it work, but i have some problems, it doesn't work like it should!
Can someone help me do it to work well and have the results that i need ?

How can i store the best number(the one closest to the random number) from every client, than to compare them(the 3 numbers, i have maximum 3 clients) again with the random number and then send a message to the clients("You guessed" for the one closest, and "Another time" for the rest of client ?)

I thought about using a vector to store those numbers and then using some if's to test wich one is the best and then figure out for wich server is the best number, and send him the msg, and to the others the other msg !

But i got stuck about using that vector to store the numbers from each child process. Can someone pls help me and show me how to do it?

Last edited by Johnny22; 02-14-2010 at 04:51 PM.. Reason: another new code
# 4  
Old 02-16-2010
I'm almost done with my program but i have a little problem, i don't know how i can check wich client had the best number.

I will explain in a few words what it does:

the server will get the 5 numbers from the clients(3) ... then it checks for each client wich number is the closest to the random number(for testing it will print the minimum difference)
the client will wait for a message.

Now i should make it to check those 3 numbers got from each client with the random number and send a mesage to the client that was the closest ?

How can i do that ?

I tried with pipes but i failed ...

Can someone pls help me ?

The code is this:

CLIENT
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>

/* codul de eroare returnat de anumite apeluri */
extern int errno;

struct operation
{
    int number1;
    int number2;
    int number3;
    int number4;
    int number5;
};

/* portul de conectare la server*/
int port;

/* programul */
int
main (int argc, char *argv[])
{
  int sd;            /* descriptorul de socket */
  struct sockaddr_in server;    /* structura folosita pentru conectare */
  struct operation request;    /* cererea trimisa clientului */
  char mesaj[100];
  
  int valid_input = 0, exit_flag = 0;

  /* exista toate argumentele in linia de comanda? */
  if (argc != 3)
    {
      printf ("Sintaxa: %s <adresa_server> <port>\n", argv[0]);
      return -1;
    }

  /* stabilim portul */
  port = atoi (argv[2]);

  /* cream socketul */
  if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      perror ("Eroare la socket().\n");
      return errno;
    }

  /* umplem structura folosita pentru realizarea conexiunii cu serverul */
  server.sin_family = AF_INET;
          /* familia socket-ului */
  server.sin_addr.s_addr = inet_addr(argv[1]);
        /* adresa IP a serverului */
  server.sin_port = htons (port);
          /* portul de conectare */

  /* ne conectam la server */
  if (connect (sd, (struct sockaddr *) &server,
           sizeof (struct sockaddr)) == -1)
    {
      perror ("Eroare la connect().\n");
      return errno;
    }

	/* citim mesajul de intampinare */
    if(recv(sd, mesaj, 100,0) < 0)
    {
		perror("Eroare la read()!\n");
		return errno;
    }
    printf("%s\n", mesaj);
	
  /* citirea mesajului si trimiterea catre server */
  bzero (&request, sizeof(struct operation));
 // printf ("Introduceti cele 5 numere: ");
  scanf ("%d %d %d %d %d", &request.number1, &request.number2, &request.number3, &request.number4, &request.number5);
  
	while(exit_flag == 0)
	{
		if((request.number1 > 0) && (request.number1 < 1000))
			exit_flag = 1;
		else
		{
			valid_input = 0;
			printf("OOPPS!Primul numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
			scanf("%d", &request.number1);
		}
		if((request.number2 > 0) && (request.number2 < 1000))
			exit_flag = 1;
		else
		{
			valid_input = 0;
			printf("OOPPS!Al doilea numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
			scanf("%d", &request.number2);
		}
		if((request.number3 > 0) && (request.number3 < 1000))
			exit_flag = 1;
		else
		{
			valid_input = 0;
			printf("OOPPS!Al treilea numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
			scanf("%d", &request.number3);
		}
		if((request.number4 > 0) && (request.number4 < 1000))
			exit_flag = 1;
		else
		{
			valid_input = 0;
			printf("OOPPS!Al patrulea numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
			scanf("%d", &request.number4);
		}
		if((request.number5 > 0) && (request.number5 < 1000))
			exit_flag = 1;
		else
		{
			valid_input = 0;
			printf("OOPPS!Al cincilea numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
			scanf("%d", &request.number5);
		}
	}
	
  fflush (stdout);
  
      request.number1 = ntohl(request.number1);
      request.number2 = ntohl(request.number2);
      request.number3 = ntohl(request.number3);
      request.number4 = ntohl(request.number4);
      request.number5 = ntohl(request.number5);


  if (send (sd, &request, sizeof(struct operation), 0) <= 0)
    {
      perror ("Eroare la write() spre server.\n");
      return errno;
    }

  int result;
  /* citirea raspunsului dat de server 
     (ne blocam pina cind serverul raspunde) */
  if (recv (sd, &result, sizeof(int), 0) < 0)
    {
      perror ("Eroare la read() de la server.\n");
      return errno;
    }
    
  result = ntohl((int)result);
  
  /* afisam mesajul primit */
  printf ("Rezultatul primit este: %d\n", result);

  /* inchidem conexiunea, am terminat */
  close (sd);
}

SERVER
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <errno.h>
#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>

const int PORT_SERVER = 6440; 			/* portul folosit */
const int CLIENTI_MAXIM = 3;			/* nr maxim de clienti acceptati */

extern int errno; 						/* eroare returnata */
int nr = 0;								/* numar de clienti */
int port;								/* portul*/
struct operation request;			   	/* cererea primita de server */
int sockfd, newsockfd, frlen, servlen;
int magic;

struct operation
{
    int number1;
    int number2;
    int number3;
    int number4;
    int number5;
};
void genereaza_numar()
{
    srand(time(NULL));
    magic = rand() % 1001;
}

/*functie de tratare a semnalelor*/
void semnal (int nr_semnal) 
{
	if (nr_semnal == SIGCHLD)
	{
		wait(NULL);
		nr--; /*s-a pierdut un client*/
		printf("A iesit clientul %d!\n", nr+1);
		fflush(stdout);
		return;
	}
}

/*operatiile pentru fiecare client*/
void doprocessing(int sock)
{
	char mesaj[100];
	
	if( nr == 0)
		printf("S-a conectat un client...Avem %d client\n", nr + 1);
	else
		printf("S-a conectat un client...Avem %d clienti\n", nr + 1);
    fflush(stdout);
	
	sprintf(mesaj, "SERVER>Sunteti clientul cu numarul %d.\nSERVER>Introduceti cele 5 numere(0..1000):", nr + 1);
    
    /* trimitem mesajul de intampinare */
    if(send(newsockfd, mesaj, strlen(mesaj),0) != strlen(mesaj))
    {
	/* Eroare! */
	shutdown(newsockfd, 2);
	exit(errno);
    } 
	 
	/* am realizat conexiunea, asteptam mesajul... */
	bzero (&request, sizeof(struct operation));
	printf ("Asteptam cererea...\n");
	fflush (stdout);
      
	/* citirea mesajului */
	int nrbytes = recv (newsockfd, &request, sizeof(struct operation), 0);
	
	/*incercam sa citim datele de la client*/
	if (nrbytes <= 0)
    {
		perror ("Eroare la read() de la client.\n");
		close (newsockfd);    /* inchidem conexiunea cu clientul */
	}
	
	/*verificam integritatea datelor*/
	if (nrbytes < sizeof(struct operation))
    {
		perror ("Date primite incomplet\n");
		close (newsockfd);
    }
	
	request.number1 = ntohl(request.number1);
    request.number2 = ntohl(request.number2);
    request.number3 = ntohl(request.number3);
    request.number4 = ntohl(request.number4);
	request.number5 = ntohl(request.number5);

	printf ("Cerere primita... \n           In curs de rezolvare: %d %d %d %d %d \n", 
											request.number1, request.number2, request.number3, request.number4, request.number5);
      
      
	/* rezolvarea cererii */

	int a=0;
	int b=0;
	int c=0;
	int d=0;
	int e=0;
	int min=0;
	int result=0;

	/* diferenta dintre numarul magic si numerele primite */
	if (magic >= request.number1)
		a = magic - request.number1;
	else
		a = request.number1 - magic;

	if (magic >= request.number2)
		b = magic - request.number2;
	else
		b = request.number2 - magic;

	if (magic >= request.number3)
		c = magic - request.number3;
	else
		c = request.number3 - magic;

	if (magic >= request.number4)
		d = magic - request.number4;
	else
		d = request.number4 - magic;

	if (magic >= request.number5)
		e = magic - request.number5;
	else
		e = request.number5 - magic;

	printf("Diferentele numerelor sunt: %d %d %d %d %d\n", a, b, c, d, e);
	
	/* verificare care numar este mai aproape de numarul magic */
	if (a > b)
		min = b;
	else 
		min = a;

	if (min > c)
		min = c;

	if (min > d)
		min = d;

	if (min > e)
		min = e;
	
	printf("Diferenta minima este: %d\n", min);
	printf("a= %d, b= %d, c= %d, d= %d, e= %d\n", a, b, c, d, e);
	
	/*selectam numarul care este mai apropiat de numarul magic*/
	if(min == a) 
		result = request.number1;
	else
		if (min == b) 
			result = request.number2;
		else 
			if (min == c)  
				result = request.number3;
			else 
				if (min == d) 
					result = request.number4;
				else
					result = request.number5;
		
	printf("result = %d\n", result);
	
	printf("TEST %d\n", magic);
	printf("Numarul cel mai apropiat de cel random a fost: %d\n", result);
		
    result = htonl(result);
	
	/* returnam rapunsul clientului */
    if (send (newsockfd, &result, sizeof(int),0) <= 0)
    {
		perror ("Eroare la write() catre client.\n");
    }
    else
		printf ("Trasmitere cu succes.\n");
      /* am terminat cu acest client, inchidem conexiunea */
      close (newsockfd);
}

/*programul principal*/
int main (int argc, char * argv[])
{
	struct sockaddr_in server , from;    	/* structurile folosite de server si client */
	int port;								/* portul */
	int pid;								/* Process ID from fork() */

	
	/* setare port in cazul specificarii explicite */
	if (argc > 1)
	{
		port = atoi(argv[1]);
	}
	else
		port = PORT_SERVER;
	
	genereaza_numar();
    printf("Numarul generat este %d\n", magic);
	
	/*tratarea semnalele*/
	if (signal (SIGCHLD, semnal) == SIG_ERR)
	{
		perror("signal()");
		exit(errno);
	}
	
	/* cream un socket */
	sockfd = socket(AF_INET, SOCK_STREAM,0);
	if (sockfd <0)
	{
		perror("Eroare la socket().");
		exit(1);
	}
	
	frlen = sizeof (from);
	servlen = sizeof (server);
	
	/* pregatim structurile de date */
	bzero (&server, servlen);
	bzero (&from, frlen);
  
	/* umplem structura folosita de server */
	server.sin_family = AF_INET;    					/* stabilirea familiei de socket-uri */
	server.sin_addr.s_addr = htonl (INADDR_ANY);		/* acceptam orice adresa */
	server.sin_port = htons (port);						/* utilizam un port utilizator */
	
	/* atasam socketul */
	if (bind (sockfd, (struct sockaddr *) &server, sizeof(struct sockaddr)) == -1)
    {
		perror ("Eroare la bind().\n");
		exit(1);
    }
	
	/* punem serverul sa asculte daca vin clienti sa se conecteze */
	if (listen (sockfd, 3) == -1)
    {
		perror ("Eroare la listen().\n");
		exit(1);
    }
		
		printf ("Asteptam la portul %d...\n", port);
		fflush (stdout);
	
	/*servim in mod concurent clientii*/
	while (1) 
    {
        newsockfd = accept(sockfd, (struct sockaddr *) &from, &frlen);
        if (newsockfd < 0)
        {
            perror("Eroare la accept().\n");
            exit(1);
        }
		
		/* Verificam daca am ajuns la numarul maxim de clienti */
		if (nr == CLIENTI_MAXIM)
		{
			perror("Numar maxim de clienti atins. Incercati mai tarziu.\n");
			shutdown(newsockfd,2);
			continue;
		}
		
        /* Cream procesul copil*/
        pid = fork();
        if (pid < 0)
        {
            perror("Eroare la fork().\n");
			exit(1);
        }
        if (pid == 0)  
        {
            /* Procesul parcurs de client */
            close(sockfd);
            doprocessing(newsockfd);
            exit(0);
        }
        else
        {
            close(newsockfd);
        }
		nr++;
    }
}



---------- Post updated 02-16-10 at 03:49 PM ---------- Previous update was 02-15-10 at 07:02 PM ----------

Can't anyone help me with my program ?

LE: I improved a little the program, but still cand save the best number and send a specific message for each client

Last edited by Johnny22; 02-17-2010 at 04:29 PM.. Reason: I improved a little the program, but still cand save the best number and send a specific message for each client
# 5  
Old 02-18-2010
HERE is the functional program Smilie.

CLIENT

Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>


extern int errno;	/* codul de eroare returnat de anumite apeluri */
int exit_flag;		/*conditie de iesire in while*/
int port;			/* portul de conectare la server*/

struct operation
{
    int number1;
    int number2;
    int number3;
    int number4;
    int number5;
};

/* programul */
int main (int argc, char *argv[])
{
  int sd;          				  /* descriptorul de socket */
  struct sockaddr_in server;    /* structura folosita pentru conectare */
  struct operation request;    /* cererea trimisa clientului */
  char mesaj[100];				
  
  
  /* exista toate argumentele in linia de comanda? */
  if (argc != 3)
    {
      printf ("Sintaxa: %s <adresa_server> <port>\n", argv[0]);
      return -1;
    }

  /* stabilim portul */
  port = atoi (argv[2]);

  /* cream socketul */
  if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      perror ("Eroare la socket().\n");
      return errno;
    }

  /* umplem structura folosita pentru realizarea conexiunii cu serverul */
  server.sin_family = AF_INET;
          /* familia socket-ului */
  server.sin_addr.s_addr = inet_addr(argv[1]);
        /* adresa IP a serverului */
  server.sin_port = htons (port);
          /* portul de conectare */

  /* ne conectam la server */
  if (connect (sd, (struct sockaddr *) &server,
           sizeof (struct sockaddr)) == -1)
    {
      perror ("Eroare la connect().\n");
      return errno;
    }

	/* citim mesajul de intampinare */
    if(recv(sd, mesaj, 100,0) < 0)
    {
		perror("Eroare la read()!\n");
		return errno;
    }
    printf("%s\n", mesaj);
	
  /* citirea mesajului si trimiterea catre server */
  bzero (&request, sizeof(struct operation));
 // printf ("Introduceti cele 5 numere: ");
  scanf ("%d %d %d %d %d", &request.number1, &request.number2, &request.number3, &request.number4, &request.number5);
  
  while (exit_flag == 0)
  {
	if((request.number1 > 0) && (request.number1 < 1000))
		if((request.number2 > 0) && (request.number2 < 1000))
			if((request.number3 > 0) && (request.number3 < 1000))
				if((request.number4 > 0) && (request.number4 < 1000))
					if((request.number5 > 0) && (request.number5 < 1000))
						exit_flag = 1;
					else
						{
							printf("OOPPS!5 numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
							scanf("%d", &request.number5);
						}
				else
					{
						printf("OOPPS!4 numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
						scanf("%d", &request.number4);
					}
			else
				{
					printf("OOPPS!3 numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
					scanf("%d", &request.number3);
				}
		else
			{
				printf("OOPPS!2 numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
				scanf("%d", &request.number2);
			}
	else
		{
			printf("OOPPS!Primul numar NU este intre 0 si 1000!\nIncercati un nou numar in acest interval!\n");
			scanf("%d", &request.number1);
		}
  }
  	
  fflush (stdout);
  
      request.number1 = ntohl(request.number1);
      request.number2 = ntohl(request.number2);
      request.number3 = ntohl(request.number3);
      request.number4 = ntohl(request.number4);
      request.number5 = ntohl(request.number5);


  if (send (sd, &request, sizeof(struct operation), 0) <= 0)
    {
      shutdown(sd,2);
	  perror ("Eroare la write() spre server.\n");
      return errno;
    }

  int result;
  /* citirea raspunsului dat de server 
     (ne blocam pina cind serverul raspunde) */
  if (recv (sd, &result, sizeof(int), 0) < 0)
    {
      perror ("Eroare la read() de la server.\n");
      return errno;
    }
    
  result = ntohl((int)result);
  
  /* afisam mesajul primit */
 // printf ("Rezultatul primit este: %d\n", result);
  if(read(sd, mesaj, 100) < 0)
    {
	perror("Eroare la read()!\n");
	return errno;
    }
    printf("%s", mesaj);

  /* inchidem conexiunea, am terminat */
  close (sd);
}

SERVER

Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <errno.h>
#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>

const int PORT_SERVER = 6440; 			/* portul folosit */
const int CLIENTI_MAXIM = 3;			/* nr maxim de clienti acceptati */
const int INTERVAL = 30;				/* timp */

extern int errno; 						/* eroare returnata */
int nr = 0;								/* numar de clienti */
int port;								/* portul*/
struct operation request;			   	/* cererea primita de server */
int sockfd, newsockfd, frlen, servlen;
int magic;

struct itimerval itv;

struct operation
{
    int number1;
    int number2;
    int number3;
    int number4;
    int number5;
};
void genereaza_numar()
{
    srand(time(NULL));
    magic = rand() % 1001;
}

/*functie de tratare a semnalelor*/
void semnal (int nr_semnal) 
{
	if (nr_semnal == SIGCHLD)
	{
		wait(NULL);
		nr--; /*s-a pierdut un client*/
		printf("\nA iesit clientul %d!\n", nr+1);
		printf("\n");
		fflush(stdout);
		return;
	}
}

/* handler-ul semnalului SIGALRM */
void alarma()
{
    printf("Generam un nou numar aleator...");
    genereaza_numar();
    printf("Numarul generat este %d\n", magic);
    fflush(stdout);
    
    /* setam handler-ul din nou */
    if(signal(SIGALRM, alarma) == SIG_ERR)
    {
	perror("Eroare la signal()!\n");
	exit(errno);
    }
    
    setitimer(ITIMER_REAL, &itv, 0);
}


/*operatiile pentru fiecare client*/
void doprocessing(int sock)
{
	char mesaj[100];
	
	if( nr == 0)
		printf("S-a conectat un client...Avem %d client\n", nr + 1);
	else
		printf("S-a conectat un client...Avem %d clienti\n", nr + 1);
    fflush(stdout);
	
	sprintf(mesaj, "SERVER>Sunteti clientul cu numarul %d.\nSERVER>Introduceti cele 5 numere(0..1000):", nr + 1);
    
    /* trimitem mesajul de intampinare */
    if(send(newsockfd, mesaj, strlen(mesaj),0) != strlen(mesaj))
    {
	/* Eroare! */
	shutdown(newsockfd, 2);
	exit(errno);
    } 
	 
	/* am realizat conexiunea, asteptam mesajul... */
	bzero (&request, sizeof(struct operation));
	printf ("Asteptam cererea...\n");
	fflush (stdout);
      
	/* citirea mesajului */
	int nrbytes = recv (newsockfd, &request, sizeof(struct operation), 0);
	
	/*incercam sa citim datele de la client*/
	if (nrbytes <= 0)
    {
		perror ("Eroare la read() de la client.\n");
		close (newsockfd);    /* inchidem conexiunea cu clientul */
	}
	
	/*verificam integritatea datelor*/
	if (nrbytes < sizeof(struct operation))
    {
		perror ("Date primite incomplet\n");
		close (newsockfd);
    }
	
	request.number1 = ntohl(request.number1);
    request.number2 = ntohl(request.number2);
    request.number3 = ntohl(request.number3);
    request.number4 = ntohl(request.number4);
	request.number5 = ntohl(request.number5);

	printf ("Cerere primita... \n           In curs de rezolvare: %d %d %d %d %d \n", 
											request.number1, request.number2, request.number3, request.number4, request.number5);
      
      
	/* rezolvarea cererii */

	int a=0;
	int b=0;
	int c=0;
	int d=0;
	int e=0;
	int min=0;
	int result=0;

	/* diferenta dintre numarul magic si numerele primite */
	if (magic >= request.number1)
		a = magic - request.number1;
	else
		a = request.number1 - magic;

	if (magic >= request.number2)
		b = magic - request.number2;
	else
		b = request.number2 - magic;

	if (magic >= request.number3)
		c = magic - request.number3;
	else
		c = request.number3 - magic;

	if (magic >= request.number4)
		d = magic - request.number4;
	else
		d = request.number4 - magic;

	if (magic >= request.number5)
		e = magic - request.number5;
	else
		e = request.number5 - magic;

	printf("\n     Diferentele numerelor sunt: %d %d %d %d %d\n", a, b, c, d, e);
	
	/* verificare care numar este mai aproape de numarul magic */
	if (a > b)
		min = b;
	else 
		min = a;

	if (min > c)
		min = c;

	if (min > d)
		min = d;

	if (min > e)
		min = e;
	
	printf("     Diferenta minima este: %d\n", min);
	printf("          a= %d, b= %d, c= %d, d= %d, e= %d\n", a, b, c, d, e);
	
	/*selectam numarul care este mai apropiat de numarul magic*/
	if(min == a) 
		result = request.number1;
	else
		if (min == b) 
			result = request.number2;
		else 
			if (min == c)  
				result = request.number3;
			else 
				if (min == d) 
					result = request.number4;
				else
					result = request.number5;
		
	//printf("result = %d\n", result);
	
	//printf("TEST %d\n", magic);
	printf("Numarul cel mai apropiat de cel random a fost: %d\n", result);
	
	result = htonl(result);
	
	if (min == 0)
	{
		printf("***********************************************************************\n");
		fflush(stdout);
		printf("Clientul cu nr %d a ghicit numarul(%d)!\n", nr + 1, magic);
		printf("***********************************************************************\n");
		fflush(stdout);
		sprintf(mesaj, "    SERVER>Ai ghicit numarul!(%d)\n", magic);
	}
	else
	{
		printf("***********************************************************************\n");
		printf("Clientul cu nr %d s-a apropiat de numarul generat %d cu o diferenta de %d\n", nr + 1, magic, min);
		printf("***********************************************************************");
		fflush(stdout);
		sprintf(mesaj, "    SERVER>Nu ai ghicit numarul!(%d)\nSERVER>Te-ai apropiat de numarul generat cu o diferenta de %d\n", magic, min);
	}
	if(send(newsockfd, mesaj, strlen(mesaj),0) != strlen(mesaj))
    {
		shutdown(newsockfd, 2);
		exit(errno);
    }
		
	/* returnam rapunsul clientului */
    if (send (newsockfd, &result, sizeof(int),0) <= 0)
    {
		shutdown(newsockfd, 2);
		perror ("Eroare la write() catre client.\n");
	}
    else
		printf ("\nTrasmitere cu succes.\n\n");
      /* am terminat cu acest client, inchidem conexiunea */
      close (newsockfd);
}

/*programul principal*/
int main (int argc, char * argv[])
{
	struct sockaddr_in server , from;    	/* structurile folosite de server si client */
	int port;								/* portul */
	int pid;								/* Process ID from fork() */

	
	/* setare port in cazul specificarii explicite */
	if (argc > 1)
	{
		port = atoi(argv[1]);
	}
	else
		port = PORT_SERVER;
	
	genereaza_numar();
    printf("Numarul generat este %d\n", magic);
	
	/* setam intervalul de generare a unui numar aleatoriu la  20 secunde */
    itv.it_interval.tv_sec = 0;
    itv.it_interval.tv_usec = 0;
    itv.it_value.tv_sec = INTERVAL;
    itv.it_value.tv_usec = 0;
    setitimer(ITIMER_REAL, &itv, 0);
	
	/*tratarea semnalele*/
	if (signal (SIGCHLD, semnal) == SIG_ERR)
	{
		perror("signal()");
		exit(errno);
	}
	
	/* asociem semnalului SIGALRM un handler */
    if(signal(SIGALRM, alarma) == SIG_ERR)
    {
	perror("Eroare la signal()!\n");
	exit(errno);
    }
	
	/* cream un socket */
	sockfd = socket(AF_INET, SOCK_STREAM,0);
	if (sockfd <0)
	{
		perror("Eroare la socket().");
		exit(1);
	}
	
	frlen = sizeof (from);
	servlen = sizeof (server);
	
	/* pregatim structurile de date */
	bzero (&server, servlen);
	bzero (&from, frlen);
  
	/* umplem structura folosita de server */
	server.sin_family = AF_INET;    					/* stabilirea familiei de socket-uri */
	server.sin_addr.s_addr = htonl (INADDR_ANY);		/* acceptam orice adresa */
	server.sin_port = htons (port);						/* utilizam un port utilizator */
	
	/* atasam socketul */
	if (bind (sockfd, (struct sockaddr *) &server, sizeof(struct sockaddr)) == -1)
    {
		perror ("Eroare la bind().\n");
		exit(1);
    }
	
	/* punem serverul sa asculte daca vin clienti sa se conecteze */
	if (listen (sockfd, 3) == -1)
    {
		perror ("Eroare la listen().\n");
		exit(1);
    }
		
		printf ("Asteptam la portul %d...\n", port);
		fflush (stdout);
	
	/*servim in mod concurent clientii*/
	while (1) 
    {
        newsockfd = accept(sockfd, (struct sockaddr *) &from, &frlen);
        if (newsockfd < 0)
        {
            perror("Eroare la accept().\n");
            exit(1);
        }
		
		/* Verificam daca am ajuns la numarul maxim de clienti */
		char mesaj[100];
		if (nr == CLIENTI_MAXIM)
		{
			perror("Numar maxim de clienti atins.\n");
			sprintf(mesaj, "Numarul maxim de clienti permisi pentru conectare a fost deja atins!\nIncercati mai tarziu!\n");
			if(send(newsockfd, mesaj, strlen(mesaj),0) != strlen(mesaj))
			{
				/* Eroare! */
				shutdown(newsockfd, 2);
				exit(errno);
			}
			continue;
		}
		
        /* Cream procesul copil*/
        pid = fork();
        if (pid < 0)
        {
            perror("Eroare la fork().\n");
			exit(1);
        }
        if (pid == 0)  
        {
            /* Procesul parcurs de client */
            close(sockfd);
            doprocessing(newsockfd);
            exit(0);
        }
        else
        {
            close(newsockfd);
        }
		nr++;
    }
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. AIX

Difference between concurrent and enhanced concurrent VG

Hi, What are the differences between concurrent and enhanced concurrent VGs.? Any advantages of enhanced concurrent VG over normal concurrent vg Regards, Siva (2 Replies)
Discussion started by: ksgnathan
2 Replies

2. Solaris

Too much TCP retransmitted and TCP duplicate on server Oracle Solaris 10

I have problem with oracle solaris 10 running on oracle sparc T4-2 server. Os information: 5.10 Generic_150400-03 sun4v sparc sun4v Output from tcpstat.d script TCP bytes: out outRetrans in inDup inUnorder 6833763 7300 98884 0... (2 Replies)
Discussion started by: insatiable1610
2 Replies

3. UNIX for Advanced & Expert Users

Problem with simple concurrent server example

hi all my problem is i have programmed a server to accept multiple clients through concurrent server approach https://lh3.googleusercontent.com/-hg-TSMdDj1k/UG5R7iICXaI/AAAAAAAAC5M/23_NnU5kH94/s800/concserver.png but when i try to execute the binding and connection accept works fine but the... (1 Reply)
Discussion started by: shyam.sunder91
1 Replies

4. Programming

[C++] [Unix] TCP non-blocking. Detect server disconnection procedure over, from client.

Hello! I searched forum for similar topic, with no luck, if you know one, delete this topic, and send me private message with link please. Little background: I have a lot of clients and one serwer. Client can make multiple connections on different ports and ips, but only one can be acctive... (2 Replies)
Discussion started by: ikeban
2 Replies

5. Windows & DOS: Issues & Discussions

Office server => laptop =>client server ...a lengthy and laborious ftp procedure

Hi All, I need your expertise in finding a way to solve my problem.Please excuse if this is not the right forum to ask this question and guide me to the correct forum,if possible. I am a DBA and on a daily basis i have to ftp huge dump files from my company server to my laptop and then... (3 Replies)
Discussion started by: kunwar
3 Replies

6. Programming

Changing source port number of a TCP client packet

Hi all, I need to change the source port number of an outgoing TCP packet. First I have to bind the socket to a particular port(suppose 9001) but when I send the TCP packet I want to change the source port number lets say to 9002 still letting the socket to be bound to the same old port (9001).... (0 Replies)
Discussion started by: anuragrai134
0 Replies

7. Programming

Client/Server Socket Application - Preventing Client from quitting on server crash

Problem - Linux Client/Server Socket Application: Preventing Client from quitting on server crash Hi, I am writing a Linux socket Server and Client using TCP protocol on Ubuntu 9.04 x64. I am having problem trying to implement a scenario where the client should keep running even when the... (2 Replies)
Discussion started by: varun.nagpaal
2 Replies

8. UNIX for Advanced & Expert Users

HOW to create UDP Concurrent Server

HI I want to create a UDP concurrent server can any one give the code for UDP concurrent server (8 Replies)
Discussion started by: chanikya
8 Replies

9. Programming

tcp server listening, client connecting problems

hello everyone. I tried searching for something related to this, but I figured it was time to ask my own question. I am experiencing these problems using Ubuntu 7.04 I am starting up a TCP listener/server and once connected, will act as a communication/control link with a program on another... (3 Replies)
Discussion started by: pjwhite
3 Replies

10. IP Networking

concurrent udp server

Just like concurrent tcp server, anyone know how to design the concurrent udp server with the thread? it's best to give some basic examples,thanks (0 Replies)
Discussion started by: Frank2004
0 Replies
Login or Register to Ask a Question