socket request python code example
Example 1: send get request python socket
import 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: tcp server using sockets in python
import socket
from socket import *
import json
serverPort = 6100
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
print("The server is listening on PORT 6100")
while 1:
connectionSocket, addr = serverSocket.accept()
data = connectionSocket.recv(1024)
data_loaded = json.loads(data)
print("client Sent :\n ", data_loaded)
connectionSocket.send(str.encode("Mil gya data"))
connectionSocket.close()