1

Hopefully I can explain this without sounding like a fool. I created a client and server in python. The plan was to open a file that I have stored and read the file and display it. Server sends to client, client receives and sends and acceptance back to server.

NOW HERES MY PROBLEM/QUESTION.
Instead of opening the file and reading it, I want to use the HTTP GET Function, particularly the HEAD function. I'm having trouble getting my client and server to understand the request. I've commented out some things that I was trying to play around with. The goal is to get the HTTP HEAD function to run and display.

#server code
import socket                   # Import socket module

port = 60000                    # Reserve a port for your service.
s = socket.socket()             # Create a socket object
host = socket.gethostname()     # Get local machine name
s.bind((host, port))            # Bind to the port
s.listen(5)                     # Now wait for client connection.

print ('Server listening....')

while True:
   conn, addr = s.accept()     # Establish connection with client.
   print ('Got connection from', addr)
   data = conn.recv(1024)
   print('Server received', repr(data))

   filename='filename.html'
   f = open(filename,'rb')
   l = f.read(1024)
   #request = "HEAD //filelocation/filename.html"  #WANT THIS TO DISPLAY   INSTEAD OF OPENING A FILE
   while (l):
      conn.send(l)
      print('Sent ',repr(l))
      #conn.send(request.encode())
      #print('Sent ', repr(request) 
      l = f.read(1024)
   f.close()

   print('Done sending')
   conn.send(b'Thank you for connecting')
   conn.close()

#client code
import socket                   # Import socket module

s = socket.socket()             # Create a socket object
host = socket.gethostname()     # Get local machine name
port = 60000                    # Reserve a port for your service.

s.connect((host, port))
request = 'HEAD //afs/cad.njit.edu/u/v/a/va257/filename.html'
s.send(b" Continue ")
with open('received_file', 'wb') as f:
   print ('file opened')
   while True:
       print('receiving data...')
       data = s.recv(1024)
       print('data : ',  "\n", (data))

       if not data:
           break
       # write data to a file
       f.write(data)

f.close()
print('Successfully get the file')
s.close()
print('connection closed')
Rubén
  • 34,714
  • 9
  • 70
  • 166
VinAbb
  • 25
  • 2
  • Why are you using sockets for HTTP? It'd be much easier/better with libs like `HTTPServer` and `urllib`. If you're doing this for fun or research then you should send headers and parse them in the server. – t.m.adam Apr 06 '18 at 06:25

0 Answers0