我有这个开源代码,用于回显对Web套接字请求的响应:
_GOODBYE_MESSAGE = 'Goodbye'
def web_socket_do_extra_handshake(request):
pass # Always accept.
def web_socket_transfer_data(request):
while True:
line = request.ws_stream.receive_message()
if line == "hello":
request.ws_stream.send_message("hello was sent")
if line == "bye":
request.ws_stream.send_message("bye was sent")
if line is None:
return
#request.ws_stream.send_message(line)
if line == _GOODBYE_MESSAGE:
return
现在问题是我想修改它(transfer_data方法),以便在while循环中让它说它检查字符串行是否等于某些文本,它应该返回其他东西给客户端,如果行等于其他东西它应该返回不同的字符串。 我已经尝试了很多,但它似乎没有用,我知道这是非常基本的,但有人可以帮助我 我想要做的另一件事是能够将响应延迟添加到5秒,但导入时间不起作用。我收到错误,请帮忙。
答案 0 :(得分:3)
对于你的第一个问题,你可以说
if line == "whatever":
# do stuff here, return, whatever...
request.ws_stream.send_message(line)
else:
# do something else....
睡觉,你想要
import time
time.sleep(seconds)
如果“导入时间”行失败,则表示您的python解释器配置存在问题。
答案 1 :(得分:0)
对于控制逻辑,请查看Python documentation(链接到2.7)。
请注意,您可以将if结构修改为以下内容:
def web_socket_transfer_data(request):
while True: # This was at the wrong indent - check it was a copy-paste issue
line = request.ws_stream.receive_message()
if line is "hello":
request.ws_stream.send_message("hello was sent")
elif line is "bye": # elif is the Pythonic form of else if
request.ws_stream.send_message("bye was sent")
elif line is _GOODBYE_MESSAGE or line is None:
break # This exits the while loop and by extension the method
time.sleep(5)
至于time.sleep()的问题,您需要确保在文件开头import time
。如果这不起作用,您可能想要检查是否可以通过IDLE直接导入它。也就是说,运行IDLE并输入import time
。如果失败,请发布它返回的错误。