Software & Finance





Visual C++ - Introduction to Socket Programming





Sockets are very important for establishing communication between the server and client. A socket can be a raw socket or TCP streaming socket or a datagram socket.

Here is the sample code for client application that connects to the server and sends the data.


Source Code


  SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if(s == -1)

    {

        AfxMessageBox("Socket Initialiation Error");

        return false;

    }

    SOCKADDR_IN serveraddr;

    struct hostent *hostentry;

 

    int portno = 80;

    bool bSent = false;

   

    hostentry = gethostbyname("www.google.com");

    char *pipaddr = inet_ntoa (*(struct in_addr *)*hostentry->h_addr_list);

 

 

     memset(&serveraddr,0, sizeof(serveraddr));

     serveraddr.sin_family = AF_INET;

     serveraddr.sin_port = htons(portno);

     serveraddr.sin_addr.s_addr = inet_addr(pipaddr);

 

    //serv_addr.sa_data = htons(portno);

 

    if (connect(s,(SOCKADDR*)&serveraddr,sizeof(SOCKADDR_IN)) < 0)

    {

         AfxMessageBox("ERROR connecting to the server");

         exit(1);

    }  

 

    char sbuf[1024] = "Data", rbuf[1024];

   

    recv(s, rbuf, 1024, 0);

    send(s, sbuf, strlen(sbuf), 0);

 

Output


 

The main difference for server side sockets are that will use bind command to bind with the address and use listen command for accepting the incoming connection. Usually binding and listen part is implemented from the main thread and when there is an incoming connection, the client connection established by creating a new thread. The child thread is responsible for serving the clients request.

The datagram sockets use sendto and recvfrom functions for communication. I will create a sample fro datagram sockets in the near future and post it to this site shortly.