Write an application that uses a socket-based connection to enable a server to receive from a client a name of a file; the server should return either the file’s contents to the client, or an indication that the file does not exist.

What will be an ideal response?


```
# Set up a server that will receive a connection
# from a client, receive a file request from the client,
# return the file contents if possible, indicate if the file
# does not exist and close the connection.

import socket

HOST = "127.0.0.1"
PORT = 5000

# step 1: create a socket
mySocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )

# step 2: bind the socket
try:
mySocket.bind( ( HOST, PORT ) )
except socket.error:
print "Call to bind failed"

# step 3: prepare for a connection
mySocket.listen( 1 )

# step 4: wait for and accept a connection
connection, address = mySocket.accept()

# step 5: process connection
clientRequest = connection.recv( 1024 )

fileExists = 1 # 0 if file exists, 1 otherwise

try:

# open file for input and output
file = open( clientRequest, "r+" )
except IOError:
fileExists = 0

if fileExists:

# send each line in the file to client
for line in file.readlines():
connection.send( line )

file.close() # close the file

connection.close() # connection closes after request
```
```
# Set up a client that will allow the user to request
# a file from the server.

import socket

HOST = "127.0.0.1"
PORT = 5000

# step 1: create a socket
mySocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )

# step 2: connect to server
try:
mySocket.connect( ( HOST, PORT ) )
except socket.error:
print "Call to connect failed"

# step 3: process connection
filename = raw_input( "Request a file: " )

mySocket.send( filename )

while 1:

serverMessage = mySocket.recv( 1024 )

if not serverMessage:
break

print serverMessage,

# step 4: close connection
print "Connection terminated"
mySocket.close()
```
Request a file: sample.txt
This is a sample, multiline file.
1 2 3 4 5 6 7 8 9
This is the last line in the file.
Connection terminated

Computer Science & Information Technology

You might also like to view...

In the accompanying figure's tree diagram, all of the elements in the body are children of a single element called the _____ element.

A. base B. fundamental C. root D. key

Computer Science & Information Technology

In the URL http://www.irs.gov, gov is the ________

Fill in the blank(s) with correct word

Computer Science & Information Technology

A help desk can boost its productivity by using _____, which allows IT staff to take over a user’s workstation and provide support and troubleshooting.

A. high-level synthesis B. wireless fidelity C. word editing software D. remote control software

Computer Science & Information Technology

In a star topology, the nodes connect to a central communications device called a router.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology