我正在使用聊天应用程序,我希望服务器通过按下按钮来控制将数据刷新到客户端。我尝试通过更新全局变量来触发可以刷新数据的if语句。然而,即使全局变量更新,它仍然不会触发if语句,因为调试“打印”不起作用,我该如何解决?
这是代码
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scatter import Scatter
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.graphics.vertex_instructions import Rectangle
from kivy.graphics.context_instructions import Color
from kivy.graphics.instructions import Instruction
from kivy.base import runTouchApp
from kivy.lang import Builder
import socket
from kivy.core.window import Window
import pygame
import random
from kivy.support import install_twisted_reactor
install_twisted_reactor()
from twisted.internet import reactor, protocol, defer
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import Protocol, Factory
censored = 0
class MultiClientEcho(protocol.Protocol):
def __init__(self, factory, app):
self.factory = factory
self.app = app
def connectionMade(self):
self.factory.clients.append(self)
def dataReceived(self, data):
for client in self.factory.clients:
storedmessage = self.factory.app.handle_message(data)
global censored
if censored ==1:
print "send message"
client.transport.write(storedmessage)
elif censored ==2:
print "banned message"
client.transport.write("censored")
def connectionLost(self,reason):
self.factory.clients.remove(self)
class MultiClientEchoFactory(protocol.Factory):
protocol = MultiClientEcho
def __init__(self,app):
self.clients = []
self.app = app
def buildProtocol(self, addr):
return MultiClientEcho(self, self.app)
class ServerApp(App):
def build(self):
self.label = Label(text="server started\n")
self.approve_btn = Button(text="approve")
self.approve_btn.bind(on_release=self.send_message)
self.banned_btn = Button(text="banned")
self.banned_btn.bind(on_release=self.banned_message)
self.layout = BoxLayout(orientation='vertical', spacing=10)
reactor.listenTCP(8000, MultiClientEchoFactory(self))
self.layout.add_widget(self.label)
self.layout.add_widget(self.approve_btn)
self.layout.add_widget(self.banned_btn)
return self.layout
def send_message(self, *args):
global censored
censored = 1
self.label.text += "sent\n"
print censored
return censored
def banned_message(self, *args):
global censored
censored = 2
self.label.text += "censored\n"
print censored
return censored
def handle_message(self, msg):
self.label.text += "received: %s\n" % msg
return msg
if __name__ == '__main__':
ServerApp().run()