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...
The annotation ________ indicates that a private instance variable should be serialized.
a. XMLElement b. Element c. Marshal d. Serialize
The first cell in a sheet is A0
Indicate whether the statement is true or false
Where is the value axis found?
A) On the right side of a chart B) On the top of a chart C) On the bottom of a chart D) On the left side of a chart
Which tab in the Task Manager would you use to find out what programs are running under a certain user?s account?
A. Services B. Performance C. Networking D. User