Skip to content

Мельник Денис ПИ20-1 #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions 1.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!DOCTYPE html>
<html>
<body>
<h1>This is first file.</h1>
</body>
</html>
6 changes: 6 additions & 0 deletions 2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!DOCTYPE html>
<html>
<body>
<h1>This is second file.</h1>
</body>
</html>
73 changes: 43 additions & 30 deletions server.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
import socket

sock = socket.socket()

try:
sock.bind(('', 80))
print("Using port 80")
except OSError:
sock.bind(('', 8080))
print("Using port 8080")

sock.listen(5)

conn, addr = sock.accept()
print("Connected", addr)

data = conn.recv(8192)
msg = data.decode()

print(msg)

resp = """HTTP/1.1 200 OK
Server: SelfMadeServer v0.0.1
Content-type: text/html
Connection: close

Hello, webworld!"""

conn.send(resp.encode())

conn.close()
import datetime

def printHtml(data_in):
global HtmlVar
try:
path = data_in.split(' ')[1]
print(path)
if path == '/':
with open('C:/Users/OMEN/PycharmProjects/Web_server/1.html', 'r') as file:
HtmlVar = file.read()
else:
with open('C:/Users/OMEN/PycharmProjects/Web_server' + path, 'r') as file:
HtmlVar = file.read()
except IndexError:
with open('C:/Users/OMEN/PycharmProjects/Web_server/1.html', 'r') as file:
HtmlVar = file.read()
time = datetime.datetime.now()
DataOut = f"""HTTP/1.1 200 OK
Date: {time.strftime("%a, %d %b %Y %H:%M:%S")}
Server: SelfMadeServer v0.0.1
Content-Length: {len(HtmlVar)}
Content-Type: text/html
Connection: close
{HtmlVar}"""
return DataOut

def serverWork():
sock = socket.socket()
try:
sock.bind(('', 80))
except OSError:
sock.bind(('', 8080))
sock.listen(5)
conn, addr = sock.accept()
print("Connected", addr)
data = conn.recv(8192)
msg = data.decode()
print(msg)
data_out = printHtml(msg)
conn.send(data_out.encode())

if __name__ == '__main__':
serverWork()