【发布时间】:2014-11-27 22:31:16
【问题描述】:
我最近正在研究套接字,试图让它们在 Windows 内部的 Python 脚本 (Python3) 中工作。
这里是服务器端的 Python 脚本。
import socket
import time
MSGLEN = 2048
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 8000))
server.listen(1)
while 1:
#accept connections from outside
(clientsocket, address) = server.accept()
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = clientsocket.recv(min(MSGLEN - bytes_recd, 2048)) #should enough this row without checks if transmission guaranteed inside buffer dimension
#print(chunk)
#i=0
chunk = chunk.decode()
bytes_recd = bytes_recd + len(chunk)
chunks.append(chunk)
for i in range(bytes_recd):
if(chunk[i] == "_"):
print("Breaking(_Bad?)")
break
buff_str = chunk[:i]
print(buff_str)
if chunk == '':
print("Server notification: connection broken")
break
mex = ''.join(chunks)
print("Server notification: \n\tIncoming data: " + mex)
i=1;
while i==1:
chunk = clientsocket.recv(128)
chunk = chunk.decode()
if chunk == '':
i = 0
totalsent = 0
msg = "Server notification: data received"
while totalsent < MSGLEN:
sent = clientsocket.send(bytes(msg[totalsent:], 'UTF-8'))
if sent == 0 :
print ("Server notification: end transmitting")
break
totalsent = totalsent + sent
我正在检查何时收到“_”并在其中做出决定。这是因为我正在使用阻塞套接字。你应该忘记最后一部分和整个程序功能,因为我正在研究它,而有罪的部分就在这里:
for i in range(bytes_recd):
if(chunk[i] == "_"):
print("Breaking(_Bad?)")
break
buff_str = chunk[:i]
发生了一些奇怪的事情:检查工作正常,并通过在正确的索引值处打印其余部分来打破循环。但!出现了这个狂野且明显无意义的错误:
>>>
Breaking(_Bad?), i: 2
13
Traceback (most recent call last):
File "C:\Users\TheXeno\Dropbox\Firmwares\Altri\server.py", line 24, in <module>
if(chunk[i] == "_"):
IndexError: string index out of range
从控制台输出可以看出,它找到“_”之前的数字,在本例中是字符串“13”,位于i = 2,符合套接字接收字符串格式:“charNumber_String”。但似乎一直在计数,直到退出边界。
编辑:我不会重命名变量,但下次最好使用改进的名称,而不是“块”和“块”。
【问题讨论】:
标签: python sockets loops python-3.x indexoutofboundsexception