Thread: TCP Client Application in windows required !!

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    12

    TCP Client Application in windows required !!

    Hi, can any body send me the working code of TCP client for windows. I tried to work on the microsoft MSDN winsock one, but it didn't work for me.

    I have the TCP server application ready with me now need Client application to make request from the server . can some one help me in this regards.

    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,659
    TCP is a protocol upon which other services (HTTP, SMTP, FTP) are built.

    > I have the TCP server application ready with me now need Client application to make request from the server
    Good for you. Without seeing the port the server is listening to, and the format of the message(s) to be sent back and forth, how would we even do such a thing?

    Try theForger's Win32 API Tutorial for Win32 programming.
    Try Beej's Guide to Network Programming for network programming.

    And no, we're not here to give you large amounts of code just because your google foo isn't up to scratch.
    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
    Aug 2011
    Posts
    12

    TCP Client server model Manuplation required

    I have both the TCP server (on Cobra5329 board) and TCP cleint on (Host pc windows) running ad workinh I can request from the client and server responds me. TCP Communication is working fine.

    These are the respective code for Server and Client.


    Code:
    Tcp Client
    
    #define WIN32_LEAN_AND_MEAN
    
    #include <windows.h>
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    
    // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
    #pragma comment (lib, "Ws2_32.lib")
    #pragma comment (lib, "Mswsock.lib")
    #pragma comment (lib, "AdvApi32.lib")
    
    
    #define DEFAULT_BUFLEN 6505
    
    int __cdecl main(int argc, char **argv) 
    {
    	
        WSADATA wsaData;
        SOCKET ConnectSocket = INVALID_SOCKET;
        struct addrinfo *result = NULL,
                        *ptr = NULL,
                        hints;
    //int n=10;;
    //while (n>0) {
    
    	char string [6505];
        char *sendbuf = "This_is_a_test_This_is_a_test_This_is_a_test_";
    	int n;
    	for (n=0; n<100; n++)
    		
    	{
        memcpy (string+(n*65),sendbuf,strlen(sendbuf));
    	}
    	string [n*65]='\0';
    
    	printf ("\n string: %s\n",string);
     
        //--n;
    //}
        
    
        char recvbuf[DEFAULT_BUFLEN];
        int iResult;
        int recvbuflen = DEFAULT_BUFLEN;
        
        // Validate the parameters
        if (argc != 3) {
            printf("usage: %s Please provide server-name & port no.\n", argv[0]);
            return 1;
        }
    	printf("\nAddress: %s, Port %s\n\n",argv[1],argv[2]);
    
        // Initialize Winsock
        iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0) {
            printf("WSAStartup failed with error: %d\n", iResult);
            return 1;
        }
    
        ZeroMemory( &hints, sizeof(hints) );
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
    
        // Resolve the server address and port
        iResult = getaddrinfo(argv[1], argv[2], &hints, &result);
    
    	/*iResult = getaddrinfo("192.168.4.1", "12345", &hints, &result);*/
        if ( iResult != 0 ) {
            printf("getaddrinfo failed with error: %d\n", iResult);
            WSACleanup();
            return 1;
        }
    
        // Attempt to connect to an address until one succeeds
        for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
    
            // Create a SOCKET for connecting to server
            ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
                ptr->ai_protocol);
            if (ConnectSocket == INVALID_SOCKET) {
                printf("socket failed with error: %ld\n", WSAGetLastError());
                WSACleanup();
                return 1;
            }
    
            // Connect to server.
            iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
            if (iResult == SOCKET_ERROR) {
                closesocket(ConnectSocket);
                ConnectSocket = INVALID_SOCKET;
                continue;
            }
            break;
        }
    
        freeaddrinfo(result);
    
        if (ConnectSocket == INVALID_SOCKET) {
            printf("Unable to connect to server!\n");
            WSACleanup();
            return 1;
        }
    
    
        // Send an initial buffer
    
    //		for (int i=0; n<100; n++){
    
    			iResult = send( ConnectSocket, string, (int) strlen(string), 0 );
    			//printf("\nThis is a test\n");
    			// printf("\nMessage Sended: %s\n",sendbuf);
    			if (iResult == SOCKET_ERROR) {
    			printf("send failed with error: %d\n", WSAGetLastError());
    			closesocket(ConnectSocket);
    			WSACleanup();
    			return 1;
    			}
    			printf("Bytes Sent: %ld\n", iResult);
    
    			
    		
    			printf("\n\n Receiving Echo data !!\n\n");
    
    			// Receive until the peer closes the connection
    			
    					ZeroMemory(recvbuf,6501);
    					iResult = recv(ConnectSocket, recvbuf, 6500, 0);
    					if ( iResult > 0 ) {
    						printf("\nBytes received: %d\n\n", iResult);
    						printf("%s\n",recvbuf);
    					
    						}
    
    
    					else if ( iResult == 0 )
    					printf("\nConnection closed\n");
    					else
    					printf("recv failed with error: %d\n", WSAGetLastError());
    
    		
    		
    
    
    			 // shutdown the connection since no more data will be sent
    			 iResult = shutdown(ConnectSocket, SD_SEND);
    			 if (iResult == SOCKET_ERROR) {
    			 printf("shutdown failed with error: %d\n", WSAGetLastError());
    			 closesocket(ConnectSocket);
                 WSACleanup();
    			 return 1;
    			 }
    		
    
        // cleanup
        closesocket(ConnectSocket);
        WSACleanup();
    
    		//}
    
        return 0;
    }
    
    
    TCP Server 
    
    /* A simple server in the internet domain using TCP
       The port number is passed as an argument */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h> 
    #include <sys/socket.h>
    #include <netinet/in.h>
    
    void error(const char *msg)
    {
        perror(msg);
        exit(1);
    }
    
    int main(int argc, char *argv[])
    {
         int sockfd, newsockfd, portno;
         socklen_t clilen;
         char buffer[6502];
         struct sockaddr_in serv_addr, cli_addr;
         int n;
    	 //int m =1;
         if (argc < 2) {
             fprintf(stderr,"ERROR, no port provided\n");
             exit(1);
         }
         sockfd = socket(AF_INET, SOCK_STREAM, 0);
         if (sockfd < 0) 
            error("ERROR opening socket");
         bzero((char *) &serv_addr, sizeof(serv_addr));
         portno = atoi(argv[1]);
         serv_addr.sin_family = AF_INET;
         serv_addr.sin_addr.s_addr = INADDR_ANY;
         serv_addr.sin_port = htons(portno);
         if (bind(sockfd, (struct sockaddr *) &serv_addr,
                  sizeof(serv_addr)) < 0) 
                  error("ERROR on binding");
         listen(sockfd,5);
         clilen = sizeof(cli_addr);
         newsockfd = accept(sockfd, 
                     (struct sockaddr *) &cli_addr, 
                     &clilen);
         if (newsockfd < 0) 
              error("ERROR on accept");
    	 //while (m>0) 
    	 //{
         bzero(buffer,6502);
         n = recv(newsockfd,buffer,6500,MSG_WAITALL);
         if (n < 0) 
    	 //{
    		 error("ERROR reading from socket");
    		 //break ;
    	 //}
         // to print the sended message 
    	  printf("Message Received: %s\n",buffer);
    	 printf("\nBytes Received: %ld\n",n);
         n = write(newsockfd,buffer,n);
    	 printf("\n\n  Echoing data !!\n\n");
    	 printf("\nBytes sended: %ld\n",n);
         if (n < 0) 
    	 //{
    		 error("ERROR writing to socket");
    		 //break ;
    	 //}
    	// }
    	 shutdown(newsockfd, SHUT_RD);
    	 shutdown(newsockfd, SHUT_WR);
         shutdown(newsockfd, SHUT_RDWR);
    	 close(newsockfd);
         close(sockfd);
         return 0; 
    }

    thisd programm sends 6500 bytes from client to the server and server resends back the same data.

    Now I want to send the data ion loops like 100 times from the client and server responds me 100 times . That is I want to repeat this communication cycle and then have to measure the time duration on cycle .

    Can anybody please help me is this regard

    Thanks

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    So wrap up the sending code on the host in a function, say called 'sendAndReceiveItAllOnce()'

    Then main becomes
    Code:
    for ( i = 0 ; i < 100 ; i++ ) {
      t1 = time();
      sendAndReceiveItAllOnce();
      t2 = time();
    }


    char string [6505]; char *sendbuf = "This_is_a_test_This_is_a_test_This_is_a_test_ "; ...
    for (n=0; n<100; n++) memcpy (string+(n*65),sendbuf,strlen(sendbuf));
    This seems like a buffer overrun to me.

    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Altenative Client Application.
    By lvandaz in forum C Programming
    Replies: 8
    Last Post: 05-01-2011, 08:34 AM
  2. Win32 Server\Client Application
    By IndioDoido in forum Windows Programming
    Replies: 7
    Last Post: 11-09-2008, 05:00 PM
  3. server client application - (i really need your help)
    By sarahnetworking in forum C Programming
    Replies: 3
    Last Post: 03-01-2008, 10:54 PM
  4. Windows form application and Windows application
    By |Wiz| in forum Windows Programming
    Replies: 5
    Last Post: 10-01-2005, 04:14 PM
  5. Client application having problem receiving from server side?
    By dp_76 in forum Networking/Device Communication
    Replies: 2
    Last Post: 08-04-2005, 02:58 PM