Версия 04

Сервер берёт информацию из txt, клиент берёт информацию с сервера
Одновление данных сервера происходит раз в секунду
This commit is contained in:
Антон Перегудин 2024-04-15 23:22:47 +03:00
parent a772870ab1
commit c51c8b7066
4 changed files with 86 additions and 39 deletions

View File

@ -1,13 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to My Website!</h1>
<p>Today is a beautiful day!</p>
<p>Feel free to explore.</p>
<p>Visit our <a href="/page1">Page 1</a>.</p>
<img src="https://toppng.com/uploads/preview/evidence-300x300-golden-baby-11564146233t27ef46tra.png" alt="Placeholder Image">
</body>
</html>

View File

@ -1,14 +1,53 @@
import tkinter as tk
import tkinter.scrolledtext as scrolledtext
import socket
from bs4 import BeautifulSoup
HOST = 'localhost'
PORT = 8080
class ClientApp:
def __init__(self, root):
self.root = root
root.title("HTTP Client")
self.text_area = scrolledtext.ScrolledText(root, width=50, height=20, wrap=tk.WORD)
self.text_area.pack(pady=10)
# Запускаем бесконечный цикл через 1 секунду после инициализации приложения
root.after(1000, self.get_data)
def get_data(self):
HOST = 'localhost'
PORT = 8080
def http_client():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((HOST, PORT))
client.sendall(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
response = client.recv(1024)
print('Response:', response.decode('utf-8'))
response = client.recv(4096)
self.display_table(response.decode('utf-8'))
if __name__ == '__main__':
http_client()
# Повторяем операцию через 1 секунду
self.root.after(1000, self.get_data)
def display_table(self, response):
self.clear_text() # Очищаем текстовое поле перед отображением новых данных
soup = BeautifulSoup(response, 'html.parser')
table = soup.find('table')
if table:
rows = table.find_all('tr')
for row in rows:
cols = row.find_all(['th', 'td'])
row_data = [col.get_text() for col in cols]
self.text_area.insert(tk.END, '\t'.join(row_data) + '\n')
self.text_area.insert(tk.END, '\n')
else:
self.text_area.insert(tk.END, "No table found in the response.")
def clear_text(self):
self.text_area.delete('1.0', tk.END) # Удаляем все содержимое текстового поля
def main():
root = tk.Tk()
app = ClientApp(root)
root.mainloop()
if __name__ == "__main__":
main()

View File

@ -2,6 +2,27 @@ import socket
PORT = 8080
HOST = 'localhost'
TABLES_FILE = 'tables.txt'
def read_text_data(filename):
with open(filename, 'r') as file:
data = file.read()
return data
def generate_html_table(data):
lines = data.strip().split('\n')
html = "<html><head><title>Table Data</title></head><body>"
html += "<table border='1'><tr>"
for header in lines[0].split(', '):
html += f"<th>{header}</th>"
html += "</tr>"
for line in lines[1:]:
html += "<tr>"
for item in line.split(', '):
html += f"<td>{item}</td>"
html += "</tr>"
html += "</table></body></html>"
return html
def http_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
@ -12,24 +33,20 @@ def http_server():
while True:
conn, addr = server.accept()
with conn:
print('Connected by', addr)
request = conn.recv(1024).decode('utf-8')
print('Request:', request)
method, path, *_ = request.split()
if method == 'GET':
if path == '/':
with open('index.html', 'rb') as file:
content = file.read()
response = b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n' + content
elif path == '/page1':
response = b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nThis is page 1'
if path == '/': # Отвечаем на все GET запросы
data = read_text_data(TABLES_FILE)
html_table = generate_html_table(data)
response = f'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n{html_table}'.encode()
else:
response = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\nPage not found'
else:
response = b'HTTP/1.1 405 Method Not Allowed\r\nContent-Type: text/html\r\n\r\nMethod not allowed'
response = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\nFile not found'
conn.sendall(response)

4
tables.txt Normal file
View File

@ -0,0 +1,4 @@
Name, Age, Occupation
John, 34, Engineer
Alice, 25, Doctor
Bob, 35, Teacher