我正在尝试从 MyTCPHandler 获取输入到以下程序中的类 Network 中。因此,理想情况下,例如,我想从 MyTCPHandler 获取 self.data 并更改 Network 中的 self._title。像往常一样,我为这个简单的问题道歉,但我对 python 中的类很陌生,我在这个问题上有点挣扎。谢谢你的帮助!
from Tkinter import *
import time
import math
import lockfile
import functions
import SocketServer
import threading
class Network(Frame):
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
HOST, PORT = "192.168.2.3", 9999
self._server = SocketServer.TCPServer((HOST, PORT),MyTCPHandler)
t = threading.Thread(target=self._server.serve_forever)
t.setDaemon(True)
t.start()
self._title="hello"
self.makeWidgets()
def makeWidgets(self):
""" Make the time label. """
self._canvas = Canvas(self, width=600, height=400)
self._canvas.pack()
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
#I want to set the above title to "self.data"
self.request.sendall(self.data.upper())
def main():
root = Tk()
#sw = StatusTable(root)
#sw.pack(side=RIGHT)
nw = Network(root)
nw.pack(side=TOP)
root.mainloop()
if __name__ == '__main__':
main()
我仍在为此苦苦挣扎,我当前的代码如下。我有两个问题。
1. 理想情况下,我想在 Network 类中设置 IP 地址,这可能吗?2. self._server 似乎没有属性“_title”,这是我试图从 MyTCPHandler 传递的属性。
from Tkinter import *
import time
import math
import lockfile
import functions
import SocketServer
import threading
class Network(Tk):
def __init__(self,server):
Tk.__init__(self)
self._server=server
t = threading.Thread(target=self._server.serve_forever)
t.setDaemon(True) # don't hang on exit
t.start()
self.makeWidgets()
def makeWidgets(self):
""" Make the time label. """
self._canvas = Canvas(self, width=600, height=400)
self._canvas.pack()
radius=20
l = Label(self,text=self._server._title)
l.pack(fill=X, expand=NO, pady=2, padx=2)
class MyTCPHandler(SocketServer.BaseRequestHandler):
def __init__(self):
self._title=StringVar()
self._title="test"
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
self._title="change"
print "changed?"
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
def main():
HOST, PORT = "10.0.1.08", 9999
print HOST
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT),MyTCPHandler)
#sw = StatusTable(root)
#sw.pack(side=RIGHT)
nw = Network(server)
nw.mainloop()