- google.appengine.api.background_thread 确实在开发服务器上工作
- 我不知道这是否是多人游戏的合理方法
例子:
前端:
<script>
onMessage = function(msg){
console.log(msg.data)
}
channel = new goog.appengine.Channel('{{ token }}');
socket = channel.open();
socket.onmessage = onMessage;
</script>
测试后端.py
import logging, webapp2, time
from google.appengine.api import background_thread, channel
class Thread(webapp2.RequestHandler):
def post(self):
token = self.request.get("token")
t = background_thread.BackgroundThread(target=timed_message, args=[token])
t.start()
def timed_message(token, *kwargs):
logging.info(token)
time.sleep(2)
channel.send_message(token, "channel works")
pages = [
("/testbackend/start_thread", Thread),
]
app = webapp2.WSGIApplication(pages, debug=True)
主文件
import webapp2, jinja2, os, logging
from google.appengine.api import backends, urlfetch, users, channel
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class IndexPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
token = channel.create_channel(user.user_id())
template_values = {"token":token}
template = JINJA_ENVIRONMENT.get_template('templates/index.html')
self.response.write(template.render(template_values))
class TestAReq(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
url = backends.get_url("testbackend")+"/testbackend/start_thread"
result = urlfetch.fetch(url, method="POST", payload="token="+user.user_id())
self.response.write("abc")
pages = [
('/', IndexPage),
("/ajaxtest", TestAReq),
]
app = webapp2.WSGIApplication(pages, debug=True)
app.yaml 处理程序:
handlers:
- url: /static
static_dir: static
- url: /testbackend/.*
script: testbackend.app
- url: /.*
script: main.app