Created
March 2, 2019 01:15
-
-
Save keyur2maru/564abe344f59ee4dd59ae42b7879a394 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from socket import * | |
import os | |
import threading | |
import datetime | |
import http.server | |
import socketserver | |
serverIp = "localhost" | |
serverPort = 9998 | |
# Create Socket | |
serverSocket = socket(AF_INET, SOCK_STREAM) | |
# Port Binding | |
serverSocket.bind((serverIp, serverPort)) | |
serverSocket.listen(500) | |
print("Listening Server on address {}:{}".format(serverIp, serverPort)) | |
# printing message so user can understand that server is ready to listen | |
print("Server is now accepting"); | |
def handle_client_connection(client_socket, request, fileName, userinput, file): | |
print("Received {}".format(request)) | |
if userinput == "GET": | |
if os.path.exists("index.html"): | |
f1 = open(os.getcwd() + "/index.html", "rb") | |
data = f1.read() | |
client_socket.sendall("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n".encode() + data) | |
print("Successful Data Transmission") | |
else: | |
print("404 not found!!") | |
client_socket.close() | |
elif userinput == "PUT": | |
print("PUT") | |
f1 = open(fileName, "wb") | |
f1.write(file) | |
client_socket.send("Upload Successful".encode()) | |
client_socket.close() | |
elif userinput == "HEAD": | |
print("HEAD") | |
client_socket.close() | |
elif userinput == "DELETE": | |
print("DELETE") | |
if os.path.exists(fileName): | |
os.remove(fileName) | |
if os.path.exists(fileName): | |
print("Upload Unsuccessfull") | |
else: | |
print("Successfully deleted!!") | |
else: | |
print("404 not found!!") | |
client_socket.close() | |
else: | |
print("Invalid input") | |
client_socket.close() | |
while True: | |
# here server accept the client and store address of client in addr and message in connectionSocket | |
client_socket, addr = serverSocket.accept() | |
request = client_socket.recv(10244) | |
print("Successfully Connected {}:{}".format(addr[0], addr[1])) | |
file, fileName, userInput, httpVersion = [str(i) for i in request.decode('utf-8').split('||')] | |
if httpVersion == "1.0": | |
print("HTTP 1.0") | |
# for i in range(1,10): | |
handle_client_connection(client_socket, request, fileName, userInput, file.encode()) | |
else: | |
print("HTTP 1.1") | |
client_handler = threading.Thread( | |
target=handle_client_connection, args=(client_socket, request, fileName, userInput, file.encode()) | |
) | |
client_handler.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment