Wednesday, September 21, 2011

simple client server socket program in c

You have now looked at enough of the socket API set to start having some fun with it. In this section, you examine, compile, and test a simple client and server process that communicates with a pair of sockets.

Writing client server using socketpair:
To keep the programming code to a bare minimum, one program will start and then fork into a client process and a server process. The child process will assume the role of the client program, whereas the original parent process will perform the role of the server. Figure 1.3 illustrates the relationship of the parent and child processes and the sockets that will be used.
Figure 1.3:
A Client / Server example using fork(2) and socketpair(2).

The parent process is the original starting process. It will immediately ask for a pair of sockets by calling socketpair(2) and then fork itself into two processes by calling fork(2).

The server will accept one request, act on that request, and then exit. The client likewise in this example will issue one request, report the server response, and then exit.

The request will take the form of the third argument to the strftime(3) function. This is a format string, which will be used to format a date and time string. The server will obtain the current date and time at the time that the request is received. The server will use the client's request string to format it into a final string, which is returned to the client. By way of review, the strftime(3) function's synopsis is as follows:

Example Code:

No comments:

Post a Comment