我是套接字的新手。我在Python中编写了一个简单的“代理”服务器,它只是从远程服务器捕获数据并将其发送到我的客户端(浏览器)。我想知道:有没有办法在没有time.sleep的情况下发送response_text?当我尝试删除time.sleep(0.5)
时,我只从远程服务器获取一个数据包,因此'Content-lenght'不等于包的长度,我得到一个错误(我正在使用recv( )获取大小等于buffer_size的缓冲区,因此如果服务器数据需要多于一个4096字节的包,我需要在下一个包中捕获它。使用time.sleep我从远程服务器获取所有数据包,然后我可以将数据发送到我的浏览器。难道我做错了什么?或者我只是不够了解?有人可以帮忙吗?
代码:
# coding: utf-8
import socket
import sys
import time
from thread import *
max_conn = 5
buffer_size = 4096
def proxy_server(webserver, port, conn, addr, data):
try:
remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_sock.connect((webserver, port))
remote_sock.send(data)
response_text = ''
while True:
time.sleep(0.5)
response = remote_sock.recv(buffer_size)
response_text += response
if len(response) < buffer_size:
remote_sock.close()
break
conn.sendall(response_text)
conn.close()
except socket.error, msg:
print 'Proccessing error. Error Code: ' + str(msg[0]) + ', Wiadomość: ' + msg[1]
remote_sock.close()
conn.close()
sys.exit()
def conn_string(conn, data, address):
header = data.split('\r\n')
method, address, protocol = header[0].split(' ')
host_key, host_value = header[1].split(': ')
proxy_server(host_value, 80, conn, address, data)
def start():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 8001))
sock.listen(max_conn)
print 'Proxy: on'
except socket.error, msg:
print 'Failed creating a socket. Error Code: ' + str(msg[0]) + ', Wiadomość: ' + msg[1]
sys.exit()
while True:
try:
connection, address = sock.accept()
data = connection.recv(buffer_size)
# start_new_thread(conn_string, (connection, data, address))
conn_string(connection, data, address)
except KeyboardInterrupt:
sock.close()
print "Socket closed"
sys.exit()
if __name__ == "__main__":
start()
答案 0 :(得分:1)
请勿使用time.sleep()
,这会使您的代理非常变慢,效率不高。
您需要将套接字设置为非阻塞模式,并且超时
您可以使用socket.settimeout()
执行此操作
我对你的proxy_server
做了一些修改,现在应该快得多。
def proxy_server(webserver, port, conn, addr, data):
try:
remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_sock.connect((webserver, port))
remote_sock.send(data)
remote_sock.settimeout(0.5)
response_text = ''
while True:
try :
response = remote_sock.recv(buffer_size)
if len(response) == 0:
break
except :
break
response_text += response
conn.sendall(response_text)
except socket.error, msg:
if str(msg) != 'timed out' :
print 'Proccessing error. Error Code: ' + str(msg[0]) + ', Wiadomość: ' + msg[1]
remote_sock.close()
conn.close()
你的其余代码都很好,但你可能想使用多线程
如果要同时处理多个客户端。