Advertisement
furas

Python - HTTP server

Jun 20th, 2018
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.27 KB | None | 0 0
  1. # //////////////////////////////////////////
  2. # Author: Marcin Radaszewski
  3. # Contact email: mradaszewski92@gmail.com
  4. # //////////////////////////////////////////
  5. import threading
  6. import socket
  7. from datetime import datetime
  8.  
  9.  
  10. class MainServer():
  11.  
  12.     def __init__(self, server_ip="0.0.0.0", server_port=5555):
  13.         self.ip = server_ip
  14.         self.port = server_port
  15.  
  16.     def run_server(self):
  17.         """That function is "heart" of a server, sets address ip,port and starts listening"""
  18.  
  19.         # SET SERVER OPTIONS SUCH AS: TYPE IP, SORT PROTOCOL TO SEND DATA
  20.         # BINDING IP,PORT ,THEN START LISTENING
  21.  
  22.         self.serwer_options = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  23.         self.serwer_options.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # musi być prze bind()
  24.         self.serwer_options.bind((self.ip, self.port))
  25.         print("[*]Server has been listening: [{}:{}]".format("0.0.0.0", self.port))
  26.         self.serwer_options.listen(5)
  27.  
  28.  
  29.     def accept_all_connection(self):
  30.         """ Accept all incoming connection from client, and return pair:
  31.        client socket and client addres ip witch are use letter to write data in archives"""
  32.  
  33.         self.client_socket, self.client_addres = self.serwer_options.accept()
  34.      
  35.         return self.client_socket, self.client_addres
  36.  
  37.     def send_data(self, send_to, data_to_send):
  38.         """That function send data on Client socket, 1st argument it's client socket from accept connection method,
  39.        2nd argument it data for client """
  40.  
  41.         send_to.send(data_to_send.encode('utf-8'))
  42.  
  43.     def recv_data(self, client_data):
  44.         """"Function is responsibility for receiving data"""
  45.  
  46.         # RECEIVE DATA FROM CLIENT AND ASSIGN TO VARIABLE
  47.         recived_data = client_data.recv(2048)
  48.  
  49.         # CHECK IF RRECIVED ARE NOT EMPTY THEN SAVE ALL TO ARCHIVE, DATA HAVE OWN FORMAT: [IP:PORT]->DATA
  50.         if len(recived_data) > 0:
  51.  
  52.             data_to_save = "[{}:{}]".format(self.client_addres[0],self.client_addres[1])+"-> "+str(recived_data)+"-> [{}:{}]".format(self.ip, self.port)
  53.             #self.save_data_to_archiv(data_to_save)
  54.  
  55.             # RETURN RECEIVED DATA AS TYPE-BYTE
  56.             return recived_data
  57.         else:
  58.             # IF SOMETHING GO WRONG , DO NOTHING AND RETURN None VALUE
  59.             print("[*]wrong data")
  60.             return None
  61.  
  62.     def create_table_user(self, client_ip, client_port):
  63.         """Method create table users"""
  64.         self.user_table = []
  65.  
  66.         if len(self.user_table) == 0:
  67.  
  68.             self.user_table.append((client_ip, client_port))
  69.         elif len(self.user_table) > 0:
  70.  
  71.             pair_addres_ip_port = (client_ip, client_port)
  72.             for i in range(0, len(self.user_table)):
  73.  
  74.                 if pair_addres_ip_port == self.user_table[i]:
  75.                     print("Address was added")
  76.  
  77.                 elif pair_addres_ip_port != self.user_table[i]:
  78.                     self.user_table.append(pair_addres_ip_port)
  79.         return self.user_table
  80.  
  81.     @staticmethod
  82.     def show_info(ip, port):
  83.         """Method show general information about client address - IP, PORT NUMBER"""
  84.  
  85.         # DISPLAY GENERAL INFORMATION ABOUT CLIENT ADDRESS
  86.  
  87.         line_separator = "------------------------------------------------------------------"
  88.         print(line_separator)
  89.         print("[*]Adres klienta: [{}:{}]".format(ip, port))
  90.  
  91.         print(line_separator)
  92.         print("[*]Client ip:")
  93.         print(line_separator)
  94.         # for i in range(0,len(self.user_table)):
  95.         #     print(i+1, "[{}:{}]".format(self.user_table[i][0], self.user_table[i][1]))
  96.         print("[*]Waiting")
  97.  
  98.     # @staticmethod
  99.     # def user_menu_display_on_std_out():
  100.     #     dsp_menu = """
  101.     #     [1]-Show active user
  102.     #     [2]-Enter to chat room
  103.     #     [3]-Logout/close connection
  104.     #     """
  105.     #     return dsp_menu
  106.  
  107.     # def socket_makefile_method(self):
  108.     #
  109.     #     self.serwer_options.makefile("r", newline="\n")
  110.  
  111. #----------------------------------------------------------------------------
  112.  
  113. headers = """HTTP/1.1 200 OK
  114. Date: Wed, 04 Jun 2014 20:35:29 GMT
  115. Server: Apache/2.2.17 (Unix)
  116. Set-Cookie: PHPSESSID=dc09f975147aa6011cac3177c1646625; path=/
  117. Expires: Thu, 19 Nov 1981 08:52:00 GMT
  118. Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
  119. Pragma: no-cache
  120. Content-Length: {}
  121. Keep-Alive: timeout=5, max=100
  122. Connection: Keep-Alive
  123. Content-Type: text/html
  124.  
  125. """
  126.  
  127. html = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  128. <html>
  129. <head>
  130. <title>Welcome to Python.com</title>    
  131. </head>
  132.    <body>
  133.        <h1><center>Hello Server</center></h1>
  134.    </body>
  135. </html>"""
  136.  
  137. # CREATE INSTANCE AND RUN SERVER
  138. test = MainServer("0.0.0.0", 4567)
  139. test.run_server()
  140.  
  141. try:
  142.     while True:
  143.         client_socket, client_address = test.accept_all_connection()
  144.        
  145.         date_to_write = test.recv_data(client_socket)
  146.         print(date_to_write.decode('utf-8'))
  147.        
  148.         test.show_info(client_address[0], client_address[1])
  149.        
  150.         size = len(html)
  151.         content = headers.format(size) + html
  152.         test.send_data(client_socket, content)
  153. except KeyboardInterrupt:
  154.     print('KeyboardInterrupt')
  155.     test.serwer_options.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement