我开始使用以下可用的基本代码(如http://aaugustin.github.io/websockets/中的示例代码):
import asyncio
import websockets
@asyncio.coroutine
def servePlayer(websocket, path):
yield from websocket.send("Hello World")
start_server = websockets.serve(servePlayer, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
我将此修改为类似但不再有效的东西。我不知道为什么。这是修改后的版本:
import asyncio
import websockets
class Player:
def __init__(self, connection):
self.connection = connection
def send(self, data):
print("sending")
yield from self.connection.send(data)
@asyncio.coroutine
def servePlayer(websocket, path):
player = Player(websocket)
player.send("Hello World")
start_server = websockets.serve(servePlayer, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
代码甚至没有到达“发送”行。
答案 0 :(得分:2)
您的player.send()
方法也是一个生成器;你需要委托给那个发电机:
@asyncio.coroutine
def servePlayer(websocket, path):
player = Player(websocket)
yield from player.send("Hello World")