socket python request response TCP code example
Example 1: send request to website python tcp socket
target_host = "www.google.com"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))
request = "GET / HTTP/1.1\r\nHost:%s\r\n\r\n" % target_host
client.send(request.encode())
response = client.recv(4096)
http_response = repr(response)
http_response_len = len(http_response)
gh_imgui.text("[RECV] - length: %d" % http_response_len)
gh_imgui.text_wrapped(http_response)
Example 2: python tcp socket example
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Choose mode. s - server, c - client")
mode = input("> ")
if mode == "s":
ip = input("Your computer's ip address: ")
port = 80
socket.bind((ip, port))
socket.listen(1)
sock, addr = socket.accept()
print("Client connected from", addr)
while True:
data = sock.recv(16384)
text = data.decode('utf-8')
print("Message from client:", text)
elif mode == "c":
ip = input("Server ip address: ")
socket.connect((ip, 80))
while True:
socket.send(input("Message: ").encode('utf-8'))