Modify the client-server communication program of Fig. 20.2 and Fig. 20.3 to use fork to handle client connections.

What will be an ideal response?

```
# Server that handles each client with a call to fork.

import socket, os
HOST = "127.0.0.1"
PORT = 5579

# create server socket
serverSocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )

# bind socket to address
serverSocket.bind( ( HOST, PORT ) )

# listen for connection
serverSocket.listen( 5 )

client = 0 # keep track of each client

while 1:

print "waiting for connection . . ."

# accept client connection
clientSocket, addr = serverSocket.accept()
print "Connection", client, "received from:", addr[ 0 ]

client += 1

pid = os.fork()

# the child process
if pid == 0:

# send connection message
clientSocket.send( "SERVER>>> Connection to client " +
str( client ) + " successful" )
clientMessage = clientSocket.recv( 1024 )

while clientMessage != \
( "CLIENT" + str( client ) + ">>> TERMINATE" ):

if not clientMessage:
break

print clientMessage

serverMessage = raw_input( ">>> " )

clientSocket.send( "SERVER>>> " + serverMessage )

clientMessage = clientSocket.recv( 1024 )

clientSocket.close()

serverSocket.close()
```
```
# Client side of the fork server program

import socket

HOST = "127.0.0.1"
PORT = 5579

# create client socket
clientSocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )

# connect socket to address
clientSocket.connect( ( HOST, PORT ) )

# receive first server message
serverMessage = clientSocket.recv( 1024 )

while serverMessage != "SERVER>>> TERMINATE":

if not serverMessage:
break

print serverMessage

clientMessage = raw_input( ">>>" )

clientSocket.send( "CLIENT>>> " + clientMessage )

serverMessage = clientSocket.recv( 1024 )

# close client socket
clientSocket.close()
```
Waiting for connection
Connection 1 received from: 127.0.0.1
SERVER>>> Connection to client successful
CLIENT>>> Hi to person at server
Waiting for connection
Connection 1 received from: 127.0.0.1
CLIENT>>> Hi to person at server
SERVER>>> Hi back to you--client!
SERVER>>> Connection to client successful
CLIENT>>> Hi to person at server
SERVER>>> Hi back to you--client!
CLIENT>>> TERMINATE

Computer Science & Information Technology

You might also like to view...

In Windows 7 in which of the following paths would a user with account CompTIA go to in order to view their pictures?

A. C:\Documents and Settings\CompTIA\Pictures B. C:\Users\CompTIA\MyPictures C. C:\Users\CompTIA\Documents\Pictures D. C:\Documents and Settings\CompTlA\My Documents\My Pictures

Computer Science & Information Technology

You can add semantic information to a table by using the ________________ element to mark the rows that make up the body.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology