0

我从以下有效的基本代码开始(如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()

代码甚至没有到达“发送”行。

4

1 回答 1

2

你的player.send()方法也是一个生成器;您需要委托给该生成器:

@asyncio.coroutine
def servePlayer(websocket, path):
    player = Player(websocket)
    yield from player.send("Hello World")
于 2015-05-16T19:40:46.263 回答