我需要多次从套接字读取。因为我需要在2秒内回复,所以读取应该是有效的,当我需要读取超过12,000
整数的行时(用这些整数完成的计算不需要很长时间,即{{1} })
我有以下方法:
0.015s
这可以更有效地完成,这样它不会花费2秒钟的时间来响应吗?
编辑: 输入如下所示:
import socket
host = "SOMEHOST"
port = SOMEPORT
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
def read_from_socket(client):
response = ''
char = ''
while not '\n' in char:
char = client.recv(1)
response += char
return response
for SOMEWHILE:
line = read_from_socket(client)
# do some stuff with line
client.send(SOMEANSWER)
我已根据以下评论修改了代码:
Case #SOME_NUMBER:
T N
N numbers
我得到以下输出:
def read_from_socket(client, size=1):
if size > 1:
return client.recv(size*4)
else:
response = ''
char = ''
while not '\n' in char:
char = client.recv(size)
response += char
return response
for i in SOME_RANGE:
case = read_from_socket(client)
print case
T, N = read_from_socket(client).split(' ')
numbers = read_from_socket(client, int(N)).split(' ')
numbers = filter(None, numbers)
numbers = [int(number) for number in numbers]
answer = # DO SOME STUFF WITH numbers
print "{}".format(answer)
在最后一种情况下,Case #1:
4
Case #2:
1
Case #3:
3
Case #4:
6
Case #5:
5
Case #6:
6
17 14 5 13 6 1 18 15 3 7 3 4 2 15 3 11 13 13 19 17 15 11 4 6 13 16 20 1 9 13 12 5 19 8 10 16 1 7 2 3 14 5 7 7 19 1 10 4 13 20 12 20 10 15 5 14 11 17 14 11 1 17 15 11 5 16 7 5 3 8 19 8 4 5 6 3 18 15 18 10 6 9 9 16 4 6 9 6 14 15 16 6 11 2 17 7 18 3 3 12 2 2 11 6 18 16 20 15 3 17 17 8 5 5 15 20 2 16 17 7 10 4 13 12 6 9 19 15 3 1 18 16 14 8 1 12 15 12 18 9 8 14 9 5 11 3 4 12 18 13 11 19 16 3 11 13 3 1 19 17 13 16 12 7 15 5 10 2 16 19 10 16 13 18 20 3 13 15 6 10 7 8 1 3 10 3 7 4 3 6 20 15 1 12 13 8 8 14 9 3 13 10 10 5 8 9 19 12 4 16 13 10 4 13 4 5 15 11 9 17 16 20 4 8 3 8 7 10 2 15 5 14 17 14 18 16 15 8
Traceback (most recent call last):
File "numbers.py", line 143, in <module>
numbers = read_from_socket(client, int(N)).split(' ')
ValueError: invalid literal for int() with base 10: '#7:\n'
。据我所知,N = 2400
可能大于12,000