我正在尝试使用频道实现从服务器到客户端的异步数据传输。我通读了以下链接,但无法按照代码进行操作。 https://cloud.google.com/appengine/docs/python/channel/
有人可以指出一个更完整的简单代码来理解吗?
答案 0 :(得分:2)
终于弄清楚了自己,不得不更好地理解这个理论并找到了缺失的部分。以下是我的代码
main.py
from google.appengine.api import channel
import webapp2
import jinja2
import os
import uuid
clientID_List = []
class MainHandler(webapp2.RequestHandler):
def get(self):
clientID = str(uuid.uuid4())
global clientID_List
clientID_List.append(clientID)
token = channel.create_channel(clientID)
template_values = {'token': token}
template = env.get_template('index.html')
self.response.write(template.render(template_values))
def post(self):
for item in clientID_List:
channel.send_message(str(item),"hello")
# channel.send_message(clientID, "helloWorld!")
# user = users.get_current_user()
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
app = webapp2.WSGIApplication([('/', MainHandler)], debug=True)
的index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Channel test page</h1>
<div id="div1"></div>
<input type="button" value="mybutton" onclick="sendPostMessage()" />
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
<script>
var token = "{{ token }}";
sendPostMessage = function () {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.send();
};
onOpened = function() {
// document.write('Channel opened to the server with the token '+token + '</br>');
document.getElementById("div1").innerHTML= document.getElementById("div1").innerText + "Channel opened to the server with the token :" + token + "<br />";
};
onMessage = function(message) {
document.getElementById("div1").innerHTML= document.getElementById("div1").innerHTML + "Date recieved from Server :" + message.data+ "<br />";
};
channel = new goog.appengine.Channel(token);
socket = channel.open()
socket.onopen = onOpened;
socket.onmessage = onMessage;
socket.onerror = function(e){
document.writeln("error:"+e['description']+ '</br>');
};
socket.onclose = function(){
document.writeln("close" + '</br>');
};
</script>
</body>
</html>