Thread: TCP Server with select() function

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    50

    TCP Server with select() function

    Hi.

    last night i tried to write a simple tcp server on select model in C for windows machine but there are some problems.

    Here is the code:

    Code:
    #include <stdio.h>
    #include <WinSock2.h>
    #include <time.h>
    
    
    
    main()
    {
    	WSADATA			wsadata;
    
    	SOCKET			ListeningSocket;
    	SOCKET			NewSocket;
    
    	SOCKADDR_IN		ServerAddr;
    	SOCKADDR_IN		ClientAddr;
    
    	FD_SET			fdread;
    
    	struct timeval	time;
    
    	int				port = 4444;
    	int				size;
    	int				SelectResults;
    
    	char			RcvBuff[200];
    
    	// Initialize Winsock version 2.2
    
    		WSAStartup(MAKEWORD(2,2),&wsadata);
    
    	// Initialize Socket
    
    		ListeningSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    
    	// Initialize Server's SOCKADDR struct
    
    		ServerAddr.sin_family = AF_INET;
    		ServerAddr.sin_port = htons(port);
    		ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    	// Bind Socket with SOCKADDR struct.
    
    		bind(ListeningSocket,(SOCKADDR *)&ServerAddr,sizeof(ServerAddr));
    
    	// Make socket Listening.
    
    		listen(ListeningSocket,5);
    
    	// Accept connection
    
    		size = sizeof(struct sockaddr);
    		NewSocket = accept(ListeningSocket,(SOCKADDR *)&ClientAddr,&size);
    
    		while(1)
    		{
    
    			// Initialize FD_SETS for the select function.
    
    				FD_ZERO(&fdread); // Clear the fd_set before select.
    
    				FD_SET(NewSocket,&fdread); // Assign Our Socket with fdread set.
    
    			// Seting up timer
    
    				time.tv_sec = 2;	// seconds
    				time.tv_usec = 5000; // miliseconds
    
    			// Select function.
    
    				SelectResults = select(0, &fdread, NULL, NULL, &time);
    
    			// Checking select's results.
    
    				if(SelectResults == SOCKET_ERROR)
    				{
    					printf("Hey man we have a problem with select\n");
    					break;
    				}
    
    				if(SelectResults > 0)
    				{
    					// That means we have some readable sockets.
    					// Checking if our socket (NewSocket) exists in fdread SET.
    
    					if(FD_ISSET(NewSocket,&fdread))
    					{
    						printf("Our socket exists and here is what it wants to say:\n\n");
    
    						// Recieving data from socket
    
    						memset(&RcvBuff,0,sizeof(&RcvBuff));
    						recv(NewSocket,RcvBuff,200,0);
    
    						printf("%s\n", RcvBuff);
    
    					}
    
    				}
    
    		}
    				
    }
    The first problem is that i can not connect a second client on the server.
    The second one is that if client send this: "hat" (three letters) everything goes right but if the client send "hato" (four letters) the server prints out :

    hato╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
    ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
    ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠☺
    And the third problem is that when i shutdown the client the server prints out until i close it the phrase :

    Our socket exists and here is what it wants to say:


    Our socket exists and here is what it wants to say:


    Our socket exists and here is what it wants to say:


    Our socket exists and here is what it wants to say:


    Our socket exists and here is what it wants to say:


    Our socket exists and here is what it wants to say:
    Can anyone help me fix some of these problems ?

    Thanks in advance.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Run this, see what it produces.
    Code:
    #include<stdio.h>
    int main ( ) {
      char buff[100];
      printf("%d %d\n", (int)sizeof(buff), (int)sizeof(&buff) );
      return 0;
    }

    Then study your (ab)use of sizeof.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    50
    Hmm you are right.. It prints out different numbers.. Ok problem No 2 fixed

    Thanks a lot.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > recv(NewSocket,RcvBuff,200,0);
    Next problem - if recv() actually fills the whole buffer, there is no \0 at the end for you to print with printf(%s)

    Consider this.
    Code:
    n = recv(NewSocket,RcvBuff,sizeof(RcvBuff)-1,0);
    if ( n > 0 ) {
      RcvBuff[n] = '\0';
    }
    No messy code to clear a buffer about to be overwritten anyway, and proper error checking as well.

    Add the other return results from recv() to complete.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Apr 2010
    Posts
    50
    Sorry but i didn't understand exactly how this fix my problem.

    I change to this my code:

    Code:
    if(FD_ISSET(NewSocket,&fdread))
    					{
    						printf("Our socket exists and here is what it wants to say:\n\n");
    
    						// Recieving data from socket
    
    						memset(&RcvBuff,0,sizeof(RcvBuff));
    						RecvBytes = recv(NewSocket,RcvBuff,sizeof(RcvBuff)-1,0);
    
    						if (RecvBytes > 0)
    						{
    							RcvBuff[RecvBytes] = '\0';
    							printf("%s\n", RcvBuff);
    						}
    
    					}

    and as i can understand we just put a \0 at the end of RcvBuff[] . Can't understand what changed. Still i can't connect two clients.

    Maybe i didn't understood exactly what you said...:s

    Thanks .

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Like I said, you also need to check when recv() returns 0, as this indicates the remote has disconnected.

    Not forgetting that -1 is also an error.

    > RcvBuff[RecvBytes] = '\0';
    When you have this, the memset is pointless.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Apr 2010
    Posts
    50
    here is the code now and its working good except from that i can't connect a second client .
    What if i put the listen function in a loop to make it listening continuously?

    Code:
    if(FD_ISSET(NewSocket,&fdread))
    					{
    						// Recieving data from socket
    
    						//memset(&RcvBuff,0,sizeof(RcvBuff));
    						RecvBytes = recv(NewSocket,RcvBuff,sizeof(RcvBuff)-1,0);
    
    						if (RecvBytes > 0)
    						{
    							printf("Our socket exists and here is what it wants to say:\n\n");
    							RcvBuff[RecvBytes] = '\0';
    							printf("%s\n", RcvBuff);
    						}else if(RecvBytes == 0){
    							printf("Client Disconnected");
    							break;
    						}else{
    							printf("Error"); 
    							break;
    						}
    
    					}
    Thanks a lot for your help Salem..
    Last edited by netpumber; 10-24-2011 at 10:27 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. select server writes message twice then hangs
    By Annonymous in forum Networking/Device Communication
    Replies: 13
    Last Post: 10-13-2011, 12:45 AM
  2. Select(); server help!
    By klipseracer in forum Networking/Device Communication
    Replies: 3
    Last Post: 03-02-2008, 11:16 PM
  3. Running two UDP server simultaneously using select()
    By PiJ in forum Networking/Device Communication
    Replies: 15
    Last Post: 01-31-2008, 10:49 AM
  4. Need winsock select() client & server source code or tutorial
    By draggy in forum Networking/Device Communication
    Replies: 2
    Last Post: 06-19-2006, 11:49 AM
  5. select() server
    By chrismiceli in forum Linux Programming
    Replies: 0
    Last Post: 09-09-2003, 08:56 PM