Socket连接在3次迭代后被中止 - python
我正在开发一个应用程序,想把音频流传输到网页上。当我打开连接并发送消息时,服务器和客户端都能收到这条消息 (s.send('Hi'))
。但是当我开始一个循环时,我的脚本在执行了3次后就停止了,然后就退出了。
我注意到服务器在第一次循环后出现了一个错误,提示 creating default object from empty value
import websocket
# https://github.com/liris/websocket-client
HOST = 'ws://127.0.0.1:8080'
s = websocket.create_connection(HOST)
s.send('Hii')
i = 0
while 1:
i += 1
print(i)
s.send(str(i))
time.sleep(0.5)
这是完整的错误追踪信息
1
2
3
Traceback (most recent call last):
File "E:\Redux\Win32\streamingdata.py", line 20, in <module>
s.send(str(i))
File "C:\Python33\lib\site-packages\websocket\__init__.py", line 656, in send
return self.send_frame(frame)
File "C:\Python33\lib\site-packages\websocket\__init__.py", line 680, in send_frame
l = self._send(data)
File "C:\Python33\lib\site-packages\websocket\__init__.py", line 900, in _send
return self.sock.send(data)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
问题出在哪里呢?使用纯套接字连接远程监听器时,脚本可以正常执行,服务器也能收到消息。但使用websocket时就失败了。有没有人能帮我解决这个问题?
1 个回答
1
试着把你的 time.sleep(0.5)
换成 gevent.sleep(0.5)
因为 websocket
是基于 gevent
的,所以你应该避免使用会阻塞的操作。
而 time.sleep
是一种阻塞操作,这样会导致 websocket
发送数据的时候被卡住,期间无法进行任何通信。
gevent.sleep
则可以让 gevent
的绿色线程有机会继续运行。