如何解决Python Websockets 连接被拒绝 ERR 111
我正在尝试使用 Websockets 作为网络部分在 Python 中创建一个文本游戏。使用提供的文档,一切都很好。但是,我需要创建一个 Webserver 类,以便能够注入连接,而不是将其作为参数传递给流程中存在的每个函数。这在文档中并没有真正涵盖。所以我搜索并找到了这个实现
import sys
from websockets import connect
class WebsocketHandler:
def __await__(self):
return self._async_init().__await__()
async def _async_init(self):
self._conn = connect("ws://127.0.0.1:5678/")
self.websocket = await self._conn.__aenter__()
return self
async def close(self):
await self._conn.__aexit__(*sys.exc_info())
async def send(self,message):
await self.websocket.send(message)
async def receive(self):
return await self.websocket.recv()
这对我的用例来说似乎没问题。但是尝试使用它时,我收到了 ConnectionRefused 错误 111。
这是游戏的实现(不是真正的游戏,更像是对它的模拟)。
import asyncio
from web.websockets.WebsocketHandler import WebsocketHandler
async def sendMessage(message):
ws = await WebsocketHandler()
await ws.send(message)
async def getMessage():
ws = await WebsocketHandler()
data = await ws.receive()
return data
async def startGame():
while True:
# createCharacter
# play
# time to send a message
await sendMessage("welcome choose!")
print(await getMessage())
await sendMessage("do a move!")
print(await getMessage())
await sendMessage("you did a move! do another!")
print(await getMessage())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(startGame())
完整的错误信息是这样的
Traceback (most recent call last):
File "/home/nick/147/TheScript/web/websockets/GameSim.py",line 32,in <module>
loop.run_until_complete(startGame())
File "/usr/lib/python3.7/asyncio/base_events.py",line 587,in run_until_complete
return future.result()
File "/home/nick/147/TheScript/web/websockets/GameSim.py",line 22,in startGame
await sendMessage("welcome choose!")
File "/home/nick/147/TheScript/web/websockets/GameSim.py",line 7,in sendMessage
ws = await WebsocketHandler()
File "/home/nick/147/TheScript/web/websockets/WebsocketHandler.py",line 12,in _async_init
self.websocket = await self._conn.__aenter__()
File "/usr/local/lib/python3.7/dist-packages/websockets/legacy/client.py",line 604,in __aenter__
return await self
File "/usr/local/lib/python3.7/dist-packages/websockets/legacy/client.py",line 622,in __await_impl__
transport,protocol = await self._create_connection()
File "/usr/lib/python3.7/asyncio/base_events.py",line 962,in create_connection
raise exceptions[0]
File "/usr/lib/python3.7/asyncio/base_events.py",line 949,in create_connection
await self.sock_connect(sock,address)
File "/usr/lib/python3.7/asyncio/selector_events.py",line 473,in sock_connect
return await fut
File "/usr/lib/python3.7/asyncio/selector_events.py",line 503,in _sock_connect_cb
raise OSError(err,f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1',5678)
有人知道为什么会这样吗?提前致谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。