unable to create new channel in javascript of channel API

╄→гoц情女王★ 提交于 2019-11-26 23:41:04

问题


Here is my python file

import os
from google.appengine.api import channel
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import logging


token = 'default'

class SendMessage(webapp.RequestHandler):
    def post(self):
        logging.info('Sending messgae with tokens : ' + token)
        channel.send_message(token,'Hello from the server')

class MainPage(webapp.RequestHandler):
    def get(self):
        global token
        token = channel.create_channel('ram')
        logging.info('Token : ' + token)
        channel.send_message(token,'Hello from the server')
        template_values = {'token': token}
        path = os.path.join(os.path.dirname(__file__), 'index.html')

        self.response.out.write(template.render(path, template_values))



application = webapp.WSGIApplication([
    ('/', MainPage),('/sendmessage',SendMessage)], debug=True)


def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

and HTML file

<html>
    <head> 
        <script type="text/javascript" src="https://talkgadget.google.com/talkgadget/channel.js"></script>
    </head>
    <body >
        <script>
            var state = {
                token: '{{ token }}'
            };
            var token = state.token;
            openChannel = function () {
                var channel = new goog.appengine.Channel(token.toString());
                var socket = channel.open();
                socket.onopen = function () {
                    alert('open');
                };
                socket.onmessage = function () {
                    alert('message');
                };
                socket.onerror = function () {
                    alert('error');
                };
                socket.onclose = function () {
                    alert('close');
                };
            };

            sendMessage = function () {

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/sendmessage', true);
                xhr.send();
            };
        </script>
        Hi All, <br>
        <button onclick="openChannel()">Open Connection</button>
        <button onclick="sendMessage()">Send Message</button>
    </body>
</html>

On the page there is Open Connection button that create the channel to the created token on server side. Now when I click on this button it flashes the error alert and then close alert. I want to make a channel and send message from server to the browser.

Am I missing something ?

来源:https://stackoverflow.com/questions/34332222/unable-to-create-new-channel-in-javascript-of-channel-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!