I have already converted a multi-treaded HTTP proxy ran by a socket server into a single-treaded proxy ran by Asyncio. And, it works well for HTTP. However, when I try to reproduce the same with SSL handshakes or maybe "while" statement then the server fails to exchange data. This code doesn't produce any error message, no hint. Meantime, yet still, it doesn't work. Only browser says that the requests are timed-out but that's something we already knew. Any suggestions? Thanks.
Working socket:
def proxy(host, port, conn, request):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# If successful, send 200 code response
s.connect((host, port))
reply = "HTTP/1.0 200 Connection established\r\n"
reply += "Proxy-agent: Proxy\r\n"
reply += "\r\n"
conn.sendall(reply.encode())
s.setblocking(False)
print(" HTTPS Connection Established")
while True:
try:
s.sendall(conn.recv(4096))
except socket.error as err:
pass
try:
reply = s.recv(4096)
conn.sendall(reply)
except socket.error as e:
s.close()
finally:
print(" Request of client completed...")
try:
s.close()
except NameError:
print(" Connection was already closed...")
except socket.error as err:
pass
Non-working socket with Asyncio:
async def proxy(host, port, conn, request):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
try:
# If successful, send 200 code response
s.connect((host, port))
reply = "HTTP/1.0 200 Connection established\r\n"
reply += "Proxy-agent: Proxy\r\n"
reply += "\r\n"
await loop.sock_sendall(conn, reply.encode())
s.setblocking(False)
print(" HTTPS Connection Established")
while True:
try:
req_ = await loop.sock_recv(conn, 4096)
await loop.sock_sendall(s, req_)
except socket.error as err:
s.close()
try:
ans_ = await loop.sock_recv(s, 4096)
await loop.sock_sendall(conn, ans_)
except socket.error as e:
s.close()
finally:
print(" Request of client completed...")
try:
s.close()
except NameError:
print(" Connection was already closed...")
except socket.error as err:
pass
loop
defined? Is it possible that it has an internal mutex lock it's using?