Daemon : Long running program ex- server
Asynchronous Callback Communication : where the server initiates communication with the client.
Client usually initiates the communication. A server can handle multiple client requests at a time.
Client side programming
Creating a TCP socket
sockfd = socket ( AF_INET , SOCK_STREAM , 0 ) ;
sockfd : integer descriptor used to identify the socket in future calls.
socket : function, part of sockets API.
Specify server's IP address and Port
struct sockaddr_in servaddr ;
bzero ( &servaddr , sizeof ( servaddr ) ) ; // sent entire structure to zero
servaddr.sin_family = AF_INET ; // set address family to AF_INET
servaddr.sin_port = htons ( 13 ) ; // set port no. to 13 (well known port of day-time server
inet_pton (AF_INET , argv [1] , &servaddr.sin_addr ) ;
- The above code is for filling the Internet socket address structure named servaddr of type sevaddr_in.
- bzero function is actually similar to, and simpler than memset function.
- htons function - host to network short - to convert the binary port number into specific format.
- inet_pton - presentation to numeric - to convert the ASCII command line argument into proper format.
Establish connection with server
connect ( sockfd , ( struct sockaddr * ) &servaddr , sizeof ( servaddr ) ) ;
connect - establishes TCP connection with the server specified by structure passed in arguments.
sizeof - let the compiler calculate the length of the socket address structure.
Read and Display Server's Reply
while ( ( n = read ( sockfd , recvline , MAXLINE ) ) > 0 )
{
recvline [n] = '\0' ; // null terminate the input
if ( fputs ( recvline , stdout ) == EOF )
/* print error ; */
}
We don't know if a single read will fit the server's reply, so we put it in a loop and stop if read returns 0 ( no more reply ) or less than 0 ( error ) .
Terminate Program
exit ( 0 ) ;
Unix always closes all open descriptors when a process terminates, so our TCP socket is now closed.