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
You might also like to view...
Tkinter component _________ displays text, images, lines and shapes.
Fill in the blank(s) with the appropriate word(s).
Why is it often necessary to scale or shift the values produced by rand?
What will be an ideal response?
In _______________ evaluation, the computer always skips the second comparison when using an AND operator if the first comparison is false.
Fill in the blank(s) with the appropriate word(s).
In an Excel PivotChart, what are the fields displayed in rows?
A) Legend (Series) B) Axis (Categories) C) Axis (Series) D) Legend (Categories)