Python客户端和服务器,实现HTTP GET

时间:2018-04-06 05:16:00

标签: python http get client head

希望我能解释这一点,而不是听起来像个傻瓜。我在python中创建了一个客户端和服务器。计划是打开我存储的文件并读取文件并显示它。服务器发送到客户端,客户端接收发送和接受回服务器。

现在我的问题/问题。
我没有打开文件并阅读它,而是想使用 HTTP GET 功能,尤其是 HEAD 功能。我无法让我的客户端和服务器理解请求。我已经评论了一些我试图玩的东西。目标是让HTTP HEAD功能运行并显示。

#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')

0 个答案:

没有答案