Help needed in my client/server app - Delay in displaying messages from clients.


 
Thread Tools Search this Thread
Top Forums Programming Help needed in my client/server app - Delay in displaying messages from clients.
# 1  
Old 07-17-2011
Help needed in my client/server app - Delay in displaying messages from clients.

Ok so this is what I have.

I have separate client and server codes. I initially had the server listening and accepting connections from ONE port, and it was working great.

Now, what I want to do is, enable the server to listen and accept connections on TWO OR MORE ports [say 5000 and 5340], thus, effectively creating two different "chat rooms". A bunch of clients communicate with each other and the server on the first port [5000], and a different bunch of clients communicate with each other, and the server on the other port [5340].

I have been able to get the server to listen and communicate on two different ports. But now, when I send a chat message from the client to the server, it doesn't display the message at the same time it receives it. Let me make this more clear. For example, I connect to the server on the first port. I then type two messages on the client, 'Hey' and 'Hurr Durr'. The server doesn't display anything. Now when I type 'Anyone there' on the server, it then displays 'Hey' and 'Hurr Durr' in quick succession. I've tried to find out what exactly could the problem be for hours, and I'm drawing a blank.

Could someone please guide me to what mistake have I been making?

Here is the server code : (compile in gcc and run it as (./server port1 port2), where server is the name of the exec and replace port1 and port 2 by any four digit numbers.)

Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>  //For read() and write()
#include <stdlib.h>
#include <string.h>
#include <time.h>


#define MSG_SIZE 80
#define MAX_CLIENTS 100
#define MYPORT 7400


void exitClient(int fd, fd_set *readfds, char fd_array[], 
					        int *num_clients)
  {
    int i;
    close(fd);
    FD_CLR(fd, readfds); //clear the leaving client from the set
    for (i = 0; i < (*num_clients) - 1; i++)
      {
        if (fd_array[i] == fd)
          {
            break;
          } 
      }           
    for (; i < (*num_clients) - 1; i++)
      {
        (fd_array[i]) = (fd_array[i + 1]);
      }
    (*num_clients)--;
  }


int main(int argc, char *argv[]) 
{
  int i=0;
  int port1, port2;
  int num_clients1 = 0, num_clients2 = 0;
  int server_sockfd1,server_sockfd2, client_sockfd1, client_sockfd2;

  struct sockaddr_in chatroom1, chatroom2;
  int addresslen = sizeof(struct sockaddr_in);
  struct sockaddr_storage their_addr1, their_addr2;
  socklen_t addr_size1, addr_size2;

  int fd;
  char fd_array1[MAX_CLIENTS], fd_array2[MAX_CLIENTS];
  fd_set readfds1, readfds2, testfds1, testfds2, clientfds, readfds;
  char msg[MSG_SIZE + 1];
  char kybd_msg[MSG_SIZE + 10];

  int result;
  int allowed; //for firewall
  int choice;  //for switch
  int auth; //to check validity of password
  char *viewclient_addr1, *viewclient_addr2; //for displaying address of connecting client

  time_t now;
  struct tm *tm;


  if(argc== 1 || argc == 4)
    {
      if(argc==4)
        {
          if(strcmp("-p",argv[1])==0)
            {
              sscanf(argv[2],"%i",&port1);
              sscanf(argv[3],"%i",&port2);
            }
          else
            {
              printf("Invalid parameters. Use: ./server [-p] [PORT1] [PORT2]\n");
              exit(0);
       	    }
        }
      else if(argc==1)
        {
	  port1=MYPORT;
          port2=MYPORT+1;
     	}
    
      printf("\n**SERVER APPLET**\n\n");
      printf("Recognised commands : \n");
      printf("-type -|quit|- anytime to close the server.\n");
      fflush(stdout);


     /* Create and name a socket for the server */
      server_sockfd1 = socket(AF_INET, SOCK_STREAM, 0);
      chatroom1.sin_family = AF_INET;
      chatroom1.sin_addr.s_addr = htonl(INADDR_ANY);  // inet_addr("127.0.0.1");
      chatroom1.sin_port = htons(port1);
      bind(server_sockfd1, (struct sockaddr *)&chatroom1, addresslen);
      
      server_sockfd2 = socket(AF_INET, SOCK_STREAM, 0);
      chatroom2.sin_family = AF_INET;
      chatroom2.sin_addr.s_addr = htonl(INADDR_ANY);  // inet_addr("127.0.0.1");
      chatroom2.sin_port = htons(port2);
      bind(server_sockfd2, (struct sockaddr *)&chatroom2, addresslen);


     /* Create a connection queue and initialize a file descriptor set */
      listen(server_sockfd1, 1);
      listen(server_sockfd2, 1);


      FD_ZERO(&readfds1);
      FD_ZERO(&readfds2);
      FD_SET(server_sockfd1, &readfds1);
      FD_SET(server_sockfd2, &readfds2);
      FD_SET(0, &readfds1); /* Add keyboard to file descriptor set */
      FD_SET(0, &readfds2); /* Add keyboard to file descriptor set */
     
          

     /* Now wait for clients and requests */
             while (1)
                 {
                     testfds1 = readfds1;
                     select(FD_SETSIZE, &testfds1, NULL, NULL, NULL);

                     testfds2 = readfds2;
                     select(FD_SETSIZE, &testfds2, NULL, NULL, NULL);

                                         
        /* If there is activity, find which descriptor it's on using FD_ISSET */
                     for (fd = 0; fd < FD_SETSIZE; fd++)
                         {
                             if (FD_ISSET(fd, &testfds1)||FD_ISSET(fd, &testfds2)) 
                                 {
                                     if (fd == server_sockfd1) 
                                         { /* Accept a new connection request */
                                             addr_size1 = sizeof their_addr1;
                                             client_sockfd1 = accept(server_sockfd1, (struct sockaddr *)&their_addr1, &addr_size1);

                                           /* Displays incoming client IP address */
                                             viewclient_addr1 = inet_ntoa(their_addr1);
                                             printf("Receiving incoming connection from IP address %s on port %d.\n\n",viewclient_addr1,port1);
                                             fflush(stdout);
	                                    
                                             if (num_clients1 < MAX_CLIENTS) 
                                                 {
                                                     FD_SET(client_sockfd1, &readfds1);
                                                     fd_array1[num_clients1]=client_sockfd1;
                                                     /*Client ID*/
                                                     now=time(NULL);
                                                     tm=localtime(&now);
                                                     printf("Client %d joined at %d:%d. \n\n",++num_clients1,tm->tm_hour,tm->tm_min);
                                                     fflush(stdout);
                                                     sprintf(msg,"M%2d",client_sockfd1);
                                                     /*write 2 byte clientID */
                                                     send(client_sockfd1,msg,strlen(msg),0);
                                                 }
                                             else 
                                                 {
                                                     sprintf(msg, "XSorry, too many clients. Try again later.\n");
                                                     write(client_sockfd1, msg, strlen(msg));
                                                     close(client_sockfd1);
                                                 }
                                         }


                                     if (fd == server_sockfd2) 
                                         { /* Accept a new connection request */
                                             addr_size2 = sizeof their_addr2;
                                             client_sockfd2 = accept(server_sockfd2, (struct sockaddr *)&their_addr2, &addr_size2);

                                           /* Displays incoming client IP address */
                                             viewclient_addr2 = inet_ntoa(their_addr2);
                                             printf("Receiving incoming connection from IP address %s on port %d.\n\n",viewclient_addr2,port2);
                                             fflush(stdout);
	                                     
                                             if (num_clients1 < MAX_CLIENTS) 
                                                 {
                                                     FD_SET(client_sockfd2, &readfds2);
                                                     fd_array2[num_clients2]=client_sockfd2;
                                                     /*Client ID*/
                                                     now=time(NULL);
                                                     tm=localtime(&now);
                                                     printf("Client %d joined at %d:%d. \n\n",++num_clients2,tm->tm_hour,tm->tm_min);
                                                     fflush(stdout);
                                                     sprintf(msg,"M%2d",client_sockfd2);
                                                     /*write 2 byte clientID */
                                                     send(client_sockfd2,msg,strlen(msg),0);
                                                 }
                                             else 
                                                 {
                                                     sprintf(msg, "XSorry, too many clients. Try again later.\n");
                                                     write(client_sockfd2, msg, strlen(msg));
                                                     close(client_sockfd2);
                                                 }
                                         }



                               
                                     else if (fd == 0) 
                                         { /* Process keyboard activity */
                                             fgets(kybd_msg, MSG_SIZE + 1, stdin);
                                             if (strcmp(kybd_msg, "quit\n")==0) 
                                                 {
                                                     sprintf(msg, "XServer is shutting down.\n");
                                                     for (i = 0; i < num_clients1 ; i++) 
                                                         {
                                                             write(fd_array1[i], msg, strlen(msg));
                                                             close(fd_array1[i]);
                                                         }
                                                     for (i = 0; i < num_clients2 ; i++) 
                                                         {
                                                             write(fd_array2[i], msg, strlen(msg));
                                                             close(fd_array2[i]);
                                                         }
                                                     close(server_sockfd1);
                                                     close(server_sockfd2);
                                                     exit(0);
                                                 }
                                             else 
                                                 {
                                                     sprintf(msg, "MServer : %s", kybd_msg);
                                                     for (i = 0; i < num_clients1 ; i++)
                                                         {
                                                             write(fd_array1[i], msg, strlen(msg));
                                                         }    
                                                     for (i = 0; i < num_clients2 ; i++)
                                                         {
                                                             write(fd_array2[i], msg, strlen(msg));
                                                         }                     
                                                 } 
                                         }
                                     else if(FD_ISSET(fd, &testfds1)||FD_ISSET(fd,&testfds2)) 
                                         { /*Process Client specific activity*/
                                           //read data from open socket
                                           result = read(fd, msg, MSG_SIZE);
                                           if(result==-1)
                                                {
                                                    perror("read()");
                                                }    
                                           else if(result>0)
                                               {
                                                   /*read 2 bytes client id*/
                                                   sprintf(kybd_msg,"MClient %d : ",fd);
                                                   fflush(stdout);
                                                   msg[result]='\0';
                                                   /*concatenate the client id with the client's message*/
                                                   strcat(kybd_msg,msg+1);
                                                   /*print to other clients*/
                                                   if(FD_ISSET(fd, &testfds1))
                                                     {
                                                       for(i=0;i<num_clients1;i++)
                                                         {
                                                            if (fd_array1[i]!= fd) /*dont write msg to same client*/
                                                            write(fd_array1[i],kybd_msg,strlen(kybd_msg));
                                                         }
                                                     }

                                                   if(FD_ISSET(fd, &testfds2))
                                                     {
                                                       for(i=0;i<num_clients2;i++)
                                                         {
                                                            if (fd_array2[i]!= fd) /*dont write msg to same client*/
                                                            write(fd_array2[i],kybd_msg,strlen(kybd_msg));
                                                         }
                                                     }
                                                   
                                                   /*print to server*/
                                                   now=time(NULL);
                                                   tm=localtime(&now);
                                                   printf("%d:%d : %s",tm->tm_hour,tm->tm_min,kybd_msg+1);
                                                   fflush(stdout);
                                                   /*Exit Client*/
                                                   if(msg[0] == 'X')
                                                       {
                                                           exitClient(fd,&readfds1, fd_array1,&num_clients1);
                                                       }
                                               }
                                         }

                                    

                             else if(!FD_ISSET(fd, &testfds1) && !FD_ISSET(fd, &testfds2))
                                 {
                                     /* A client is leaving */                     
                                     exitClient(fd,&readfds1, fd_array1,&num_clients1);
                                     exitClient(fd,&readfds2, fd_array2,&num_clients2);
                                 }//if
                              }//if
                         }//for


                 }//while
           }//argc if
  else
    {
      printf("Invalid parameters. Use: ./server [-p] [PORT1] [PORT2]\n");
      exit(0);
    } 
         
 }//main

And the client code : (to run it, compile using gcc and type ./client, where client is the name of the executable)
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>  //For read() and write()
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MSG_SIZE 80
#define MAX_CLIENTS 100
#define MYPORT 7400

int main(int argc, char *argv[]) 
{
  int port;
  int num_clients = 0;
  int fd;
  fd_set readfds, testfds, clientfds;
  char msg[MSG_SIZE + 1];
  char kybd_msg[MSG_SIZE + 10];
  int sockfd;
  int result;
  char hostname[MSG_SIZE];
  struct hostent *hostinfo, *hp;
  struct sockaddr_in address;
  int clientid;
  int auth;
  int i;
  char clientname[100];
  size_t size;
  time_t now;
  struct tm *tm;
  int newport;
  char cmd[100];
  
  if(argc==2) //ignore this code block
    {
      if(strcmp("other",argv[1])==0)
        {  
           printf("Enter new port : ");
           scanf("%d",&newport);
           sprintf(cmd, "./server -p %d",newport);
           printf("\n\nNew chat-room server created on port %d.\n\n",newport);
           system(cmd);
           exit(0);
        }
    }
 
  printf("*** Client applet. (type |-quit-| to close): \n");
  printf("\nPlease enter the port to connect to : ");
  scanf("%i",&port);
  printf("Please enter the address of the host to connect to : ");
  scanf("%s",hostname);
  printf("\n");
  fflush(stdout);
   
  /* Get client hostname */
  gethostname(clientname, size);
    
  /* Get client IP address from hostname */
  hp = gethostbyname (clientname);

      if (hp == NULL)
        printf ("NULL returned by gethostbyname.\n");
      else
        if ((int)hp == -1)
          printf ("-1 returned by gethostbyname.\n");
        else
          {
            printf("Name:       %s\n", hp->h_name);
              if (hp->h_addr_list == NULL)
	        printf("No address list returned.\n");
              else
                if (hp->h_addr_list[0] == NULL)
	          printf("No addresses in the address list.\n");
                else
                  {
	            printf("Addresses:  %s\n",
		    inet_ntoa(*(struct in_addr *)hp->h_addr_list[0]));
	            for (i = 1; hp->h_addr_list[i] != NULL; i++)
	              printf("            %s\n",
		    inet_ntoa(*(struct in_addr *)hp->h_addr_list[i]));
	            if (i != 1)
	              printf("                %d addresses.\n", i);
                  }
          }

      /* Create a socket for the client */
      sockfd = socket(AF_INET, SOCK_STREAM, 0);

      /* Name the socket, as agreed with the server */
      hostinfo = gethostbyname(hostname); /* look for host's name */
      address.sin_addr = *(struct in_addr *)*hostinfo -> h_addr_list;
      address.sin_family = AF_INET;
      address.sin_port = htons(port);

      /* Connect the socket to the server's socket */
      if(connect(sockfd, (struct sockaddr *)&address, 
						sizeof(address)) < 0)
        {
          perror("Error in connecting.");
          exit(1);
        }
      fflush(stdout);
      FD_ZERO(&clientfds);
      FD_SET(sockfd,&clientfds);
      FD_SET(0,&clientfds);//stdin
   
      printf("\nPlease enter your chat messages below.\n");	
     
      /* Now wait for messages from the server */
      while (1)
        {
          testfds=clientfds;
          select(FD_SETSIZE,&testfds,NULL,NULL,NULL);
          for(fd=0;fd<FD_SETSIZE;fd++)
            {
              if(FD_ISSET(fd,&testfds))
                {
                   if(fd == sockfd)
                     {  /*Accept data from open socket */
                        result = read(sockfd, msg, MSG_SIZE); 
                        msg[result] = '\0';
                        now=time(NULL);
                        tm=localtime(&now);
                        printf("%d:%d : %s",tm->tm_hour,tm->tm_min,msg +1);
                        if (msg[0] == 'X') 
                          {
                            close(sockfd);
                            exit(0);
                          }
                     }
                   else if(fd == 0)
                    { /*process keyboard activiy*/
                      fgets(kybd_msg, MSG_SIZE+1, stdin);
                      if(strcmp(kybd_msg, "quit\n")==0)
                        {
		          sprintf(msg, "X Client is shutting down.\n");
                          write(sockfd, msg, strlen(msg));
                          close(sockfd); //close current client
                          exit(0); //end program
                        }
                      else 
                        {
                          sprintf(msg, "M %s", kybd_msg);
                          write(sockfd, msg, strlen(msg));
                        }
                    }//elseif
                }//if
            }//for
        }//while
}//main

Sorry for the wall of text! :S
# 2  
Old 07-17-2011
Check security settings and see if your server allows to receive messages from clients?
# 3  
Old 07-17-2011
Well, I'm running both server and client on the same machine. The server and client ARE able to communicate, but the problem is that the server won't display anything from the client UNLESS i type something in the server, at which point it then displays all the messages recieved from the client till then. I don't think its a security issue.
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Programming

ESP32 (ESP-WROOM-32) as an MQTT Client Subscribed to Linux Server Load Average Messages

Here we go.... Preface: ..... so in a galaxy far, far, far away from commercial, data sharing corporations..... For this project, I used the ESP-WROOM-32 as an MQTT (publish / subscribe) client which receives Linux server "load averages" as messages published as MQTT pub/sub messages.... (6 Replies)
Discussion started by: Neo
6 Replies

2. UNIX for Dummies Questions & Answers

Help! needed to displaying an output in record format

Hi Friends, Am new to Unix world and this is my first post in this forum. I was stuck in displaying the content. while displaying the content the below points to be taken care 1 ) The header format is repeating 2) To display the value in table format... (2 Replies)
Discussion started by: rocky2013
2 Replies

3. Programming

Clients - Server ( UDP )

Hello, I have a question: I want to create a n client to one server connection. This is the client-server algorithm. Enybody help to make the changes? (0 Replies)
Discussion started by: MaHmur
0 Replies

4. IP Networking

Some clients cannot ping UNIX server

All of sudden in this morning, some computers could not connect to our UNIX server while other still could. Some computers could ping the server while some could not. Same on the server side. It could ping some clients but not some. All Windows clients could ping each other. And more, the... (1 Reply)
Discussion started by: jonapa
1 Replies

5. Red Hat

Configure app server to view server files

Hi, We have a OEL6.1 installed on our server. We want developers to view there application logs generated on the server, but doesn't really want to give them access to server machine. Can someone please suggest how can we configure apache/httpd to create a url which will show all files in... (1 Reply)
Discussion started by: shrshah64
1 Replies

6. UNIX for Dummies Questions & Answers

difference weblogic server/webserver/app server

Hi All, I am getting confused with the terms below. All I know is an application can be installed on a server. But I see the following terms used in a company. All of them are installed on same Unix box. Could you please help me out in layman terms as to what these exactly means. (PS: I don't... (1 Reply)
Discussion started by: tostay2003
1 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. Solaris

Solaris 8 server and Jumpstarting 2.6 clients

Ladies and Gentlemen: I have successfully configured a Solaris 8 server with Jumpstart! I can Jumpstart Solaris 8 client systems with no problem. My configuration is as follows: Jumpstart Server: Solaris 8 patched with Recommended Patches from June 05. I have installed Solaris 8 in... (4 Replies)
Discussion started by: rambo15
4 Replies

9. UNIX for Dummies Questions & Answers

client app not letting go of socket

Ok here's the situation We have an application that our users log into over the network to one of our unix boxes (Solaris 8). I had this situation occur the other day where an user claimed that he totally shutdown the app because it froze up and wasn't able to log back in. I performed a... (1 Reply)
Discussion started by: fusion99
1 Replies
Login or Register to Ask a Question