def __call__(self, env, start_response, app_instance = None): app_instance = app_instance or self http_request = HTTPRequest(env) http_request._parse_body() from gale import web handler = Application.__call__(app_instance, http_request, is_wsgi = True) if hasattr(handler, '_new_cookie'): for cookie in handler._new_cookie.values(): handler.add_header('Set-Cookie', cookie.OutputString()) status = "%s %s" % (handler._status_code, handler._status_mess) _body = b''.join(handler._push_buffer) if http_request.method == 'HEAD': # 如果是HEAD请求的话则不返回主体内容 _body = b'' if handler._status_code != 304: handler.set_header('Content-Length', len(_body)) headers = [(native_str(_k), str(native_str(_v))) for _k, _v in handler._headers.get_headers_items()] # 在python2.7 中,不允许headers是unicode write = start_response(native_str(status), headers) write(_body) handler.log_print() handler.on_finish() return []
pass def on_message(self, frame): message = frame.data if self not in ConnHandler.clients: # 表示这是新用户 ConnHandler.clients[self] = message # 这里的message就是用户的nickname self.broadcast('system', '欢迎 {nickname} 进入聊天室'.format(nickname = message)) else: self.broadcast(ConnHandler.clients[self], message) def on_close(self, code, reason): nickname = ConnHandler.clients.pop(self) self.broadcast('system', '{nickname} 离开了聊天室'.format(nickname = nickname)) def broadcast(self, _from, message): for client in ConnHandler.clients: client.send_message('{_from}: {message}'.format(_from = _from, message = message)) app = Application([(r'/conn', ConnHandler)], settings = {'debug': False, 'template_path': 'template', 'static_path': 'static'}) @app.router('/') def index(self): self.render('index.html') app.run(port = 5000, processes = 1)