test/http_socket.py

60 lines
1.8 KiB
Python

import socket
def http_via_socket():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print("Connecting to vyatsu.ru...")
client.connect(('vyatsu.ru', 80))
print("Connection established")
request = (
"GET / HTTP/1.1\r\n"
"Host: vyatsu.ru\r\n"
"User-Agent: Python-Socket-Client/1.0\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n"
"Connection: close\r\n"
"\r\n"
)
print("Sending HTTP request...")
client.sendall(request.encode())
print("Receiving response...")
response = b""
while True:
chunk = client.recv(4096)
if not chunk:
break
response += chunk
decoded_response = response.decode('utf-8', errors='ignore')
print("\n" + "="*50)
print("SERVER RESPONSE:")
print("="*50)
headers_end = decoded_response.find('\r\n\r\n')
if headers_end != -1:
headers = decoded_response[:headers_end]
body_start = headers_end + 4
body_preview = decoded_response[body_start:body_start + 500]
print("HEADERS:")
print(headers)
print(f"\nBODY (first 500 characters):")
print(body_preview)
if len(decoded_response) > body_start + 500:
print("... (response truncated)")
else:
print(decoded_response[:1000])
except Exception as e:
print(f"Error: {e}")
finally:
client.close()
print("\nConnection closed")
if __name__ == "__main__":
http_via_socket()