Compare commits

..

3 Commits

15 changed files with 287 additions and 0 deletions

22
.gitignore vendored Normal file
View File

@ -0,0 +1,22 @@
# Игнорировать файлы Python
pycache/
*.pyc
*.pyo
*.pyd
# Игнорировать файлы окружения
venv/
.venv/
# Игнорировать файлы конфигурации VS Code
.vscode/
# Игнорировать файлы с токенами
.env
token.txt
# Временные файлы
*.tmp
*.bak
*.swp
.env

View File

@ -0,0 +1,18 @@
# Лабораторная работа №3
## Описание работы
### Цель работы
Изучение сетевых соединений в Python
### Содержание работы
* Создание TCP-сервера
* Создание TCP-клиента
* Анализ трафика в Wireshark
* Работа с HTTP
* Взаимодействие с API
### Инструкция по запуску
1. Активация виртуального окружения
2. Установка зависимостей
3. Запуск программ

28
create_repo.py Normal file
View File

@ -0,0 +1,28 @@
import os
import requests
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
headers = {
"Authorization": f"token {TOKEN}"
}
data = {
"name": "lab3-api-test"
}
response = requests.post(
"https://git.vyatsu.ru/api/v1/user/repos",
headers=headers,
json=data
)
print("Статус:", response.status_code)
print(response.json())
input()

15
docs/architecture.md Normal file
View File

@ -0,0 +1,15 @@
lab3/
├── src/
│ ├── tcp_server.py
│ ├── tcp_client.py
│ ├── udp_server.py
│ ├── udp_client.py
│ └── config.py
├── tests/
│ └── test_server.py
├── docs/
│ └── architecture.md
├── README.md
├── requirements.txt
├── run.sh
└── .gitignore

23
gitea_api.py Normal file
View File

@ -0,0 +1,23 @@
import os
import requests
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
headers = {
"Authorization": f"token {TOKEN}"
}
response = requests.get(
"https://git.vyatsu.ru/api/v1/user",
headers=headers
)
print("Статус:", response.status_code)
print(response.json())
input("\nНажми Enter...")

41
http_requests.py Normal file
View File

@ -0,0 +1,41 @@
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Подключение к серверу...")
client.connect(("vyatsu.ru", 80))
request = (
"GET / HTTP/1.1\r\n"
"Host: vyatsu.ru\r\n"
"User-Agent: Mozilla/5.0\r\n"
"Accept: */*\r\n"
"Connection: close\r\n"
"\r\n"
)
print("Отправка запроса...\n")
client.sendall(request.encode())
response = b""
running = True
while running:
data = client.recv(4096)
if data:
response += data
else:
running = False
decoded = response.decode(errors="ignore")
print(decoded[:5000])
client.close()
input("\nНажми Enter...")

26
http_socket.py Normal file
View File

@ -0,0 +1,26 @@
import socket
client = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)
client.connect(("vyatsu.ru", 80))
request = (
"GET / HTTP/1.1\r\n"
"Host: vyatsu.ru\r\n"
"User-Agent: python-requests/2.32.3\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept: */*\r\n"
"Connection: keep-alive\r\n"
"\r\n"
)
client.sendall(request.encode())
response = client.recv(4096)
print(response.decode(errors="ignore"))
client.close()

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
requests

5
run.sh Normal file
View File

@ -0,0 +1,5 @@
#!/bin/bash
echo "Запуск TCP сервера"
python src/tcp_server.py &
echo "Запуск TCP клиента"
python src/tcp_client.py

4
src/config.py Normal file
View File

@ -0,0 +1,4 @@
# config.py
HOST = '127.0.0.1'
TCP_PORT = 10000
UDP_PORT = 10001

15
src/tcp_client.py Normal file
View File

@ -0,0 +1,15 @@
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 10000))
message = input("Введите сообщение: ")
client.sendall(message.encode())
data = client.recv(1024)
print(f"Ответ сервера: {data.decode()}")
client.close()

34
src/tcp_server.py Normal file
View File

@ -0,0 +1,34 @@
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 10000))
server.listen(1)
print("TCP сервер запущен")
running = True
while running:
conn, addr = server.accept()
print(f"Подключение от {addr}")
data = conn.recv(1024)
if data:
text = data.decode()
print(f"Получено: {text}")
conn.sendall(data.upper())
if text.upper() == "EXIT":
running = False
conn.close()
server.close()

20
src/udp_client.py Normal file
View File

@ -0,0 +1,20 @@
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
running = True
while running:
message = input("Введите сообщение: ")
client.sendto(message.encode(), ("127.0.0.1", 12000))
data, _ = client.recvfrom(1024)
print(f"Ответ сервера: {data.decode()}")
if message.upper() == "EXIT":
running = False
client.close()

26
src/udp_server.py Normal file
View File

@ -0,0 +1,26 @@
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(("0.0.0.0", 12000))
print("UDP сервер запущен")
running = True
while running:
data, addr = server.recvfrom(1024)
text = data.decode()
print(f"Сообщение от {addr}: {text}")
response = "СЕРВЕР: " + text[::-1]
server.sendto(response.encode(), addr)
if text.upper() == "EXIT":
running = False
server.close()

9
tests/test_server.py Normal file
View File

@ -0,0 +1,9 @@
import unittest
class TestServer(unittest.TestCase):
def test_connection(self):
# Здесь будет код теста
pass
if name == 'master':
unittest.main()