gpt4 book ai didi

javascript - 带有 Tornado 的 Websockets

转载 作者:行者123 更新时间:2023-11-30 16:13:57 24 4
gpt4 key购买 nike

我是 tornado 框架的新手,到目前为止,一切都非常困惑,尤其是在处理网络套接字时。到目前为止,我的代码如下所示:

import tornado.options
import tornado.web
import tornado.websocket
import tornado.ioloop

from tornado.options import options, define

define(name='port', default=8000, help='.', type=int)

class WSHandler(tornado.websocket.WebSocketHandler):
clients = []

def open(self):
WSHandler.clients.append(self)
self.write('client connected')

def on_close(self):
WSHandler.clients.remove(self)
self.write('client removed')

def on_message(self, message):
for client in WSHandler.clients:
WSHandler.client.write_message(message)

def check_origin(self, origin):
return True

if __name__ == '__main__':
tornado.options.parse_command_line()
application = tornado.web.Application(
handlers=[
(r'/webSocket', WSHandler),
],
)
application.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

javascript 文件看起来像这样

var ws = new WebSocket("ws://localhost:8000/webSocket")
ws.onopen = function() {
ws.setData('Hello World');
};
ws.onmessage = function(evt) {
ws.send(evt.data);
};

我目前正在阅读“ Tornado 简介”一书,并意识到某些内容现在已被弃用。我确实下载了 git-hub 上提供的演示,并尝试理解 websocket 演示。

我尝试创建一个简单的 websocket 应用程序,但它所做的只是给我这个错误:

Can "Upgrade" only to "WebSocket"

此外,我还有一个关于 Tornado 的问题
_() 是什么意思?文档中给出的例子是

_("A person liked this", "%(num)d people liked this", len(people)) % {"num": len(people)}

如果 people 中只有一个人,这应该会返回“A person liked this”。我不太明白这是怎么回事

如果我犯了一个非常明显的错误,我深表歉意

最佳答案

我想你可以看到tornado source ,您可以找到以下内容:

# Upgrade header should be present and should be equal to WebSocket
if self.request.headers.get("Upgrade", "").lower() != 'websocket':
self.set_status(400)
log_msg = "Can \"Upgrade\" only to \"WebSocket\"."
self.finish(log_msg)
gen_log.debug(log_msg)
return

很明显,HTML5 WebSocket协议(protocol)是一个新的协议(protocol)。它实现了浏览器和服务器的全双工通信(full-duplex)。但是使用http只能做单机通信。所以我建议你再试试另一个demo。

服务器:

    #!/usr/bin/python
#coding:utf-8
import os.path

import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpclient
import tornado.websocket

import json
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")

class SocketHandler(tornado.websocket.WebSocketHandler):
"""docstring for SocketHandler"""
clients = set()

@staticmethod
def send_to_all(message):
for c in SocketHandler.clients:
c.write_message(json.dumps(message))

def open(self):
self.write_message(json.dumps({
'type': 'sys',
'message': 'Welcome to WebSocket',
}))
SocketHandler.send_to_all({
'type': 'sys',
'message': str(id(self)) + ' has joined',
})
SocketHandler.clients.add(self)

def on_close(self):
SocketHandler.clients.remove(self)
SocketHandler.send_to_all({
'type': 'sys',
'message': str(id(self)) + ' has left',
})

def on_message(self, message):
SocketHandler.send_to_all({
'type': 'user',
'id': id(self),
'message': message,
})

##MAIN
if __name__ == '__main__':
app = tornado.web.Application(
handlers=[
(r"/", IndexHandler),
(r"/chat", SocketHandler)
],
debug = True,
template_path = os.path.join(os.path.dirname(__file__), "templates"),
static_path = os.path.join(os.path.dirname(__file__), "static")
)
app.listen(8000)
tornado.ioloop.IOLoop.instance().start()

客户:

    <html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8000/chat");
ws.onmessage = function(event) {
console.log(event);
}
function send() {
ws.send(document.getElementById('chat').value );
}
</script>
</head>

<body>
<div>
hello
<input id="chat">
<button onclick="send()">send</button>
</div>
</body>
</html>

关于javascript - 带有 Tornado 的 Websockets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com