环境:python2.62+tkinter,ubuntu
输入对方ip地址和端口就可以进行双方通信,界面仿照im软件设计。由于udp监听采用单独线程,tcl/tk库可能不支持,需要自行编译成多线程支持。在windows下运行正常,窗口大小需要调整一下。
#! /usr/bin/pythonfrom tkinter import *import socketimport threadingimport tkfontclass window:”’ main window”’def __init__(self, master):self.fm1 = frame(master)self.fm1.pack()#label(fm1,text=’local ip address:’).grid(row=0,sticky=w,pady=5)label(self.fm1, text=’target ip & port:’, font=ft).grid(row=1, sticky=w, pady=5)label(self.fm1, text=’message history:’, font=ft).grid(row=2, stick=w)self.ip = stringvar()self.ip.set(‘192.168.1.168’)self.port = stringvar()self.port.set(‘2345′)self.ipentry = entry(self.fm1, width=15, textvariable=self.ip, font=ft)self.ipentry.grid(row=1, column=1, sticky=w)self.portentry = entry(self.fm1, textvariable=self.port, font=ft)self.portentry.grid(row=1, column=2, sticky=w, pady=5)self.fm2 = frame(master)self.fm2.pack()self.msgshow = text(self.fm2, height=12, width=35, font=ft)self.scroll = scrollbar(self.fm2, command=self.msgshow.yview)self.msgshow.configure(yscrollcommand=self.scroll.set)self.msgshow.pack(side=left, pady=5)self.scroll.pack(side=right, fill=y)label(master, text=’write your message below:’, font=ft).pack()self.msgwrite = text(master, height=3, width=50, font=ft)self.msgwrite.pack(pady=5)self.msgwrite.focus_set()self.msgwrite.bind(”, self.sendmsg)label(root, text=’press ctrl+enter to send message’, font=ft).pack(side=bottom)def sendmsg(self, event=none):self.msg = self.msgwrite.get(1.0, end)self.msgshow.insert(end, ‘send: ‘ + self.msg)self.msgshow.see(end)self.msgwrite.delete(1.0, end)mysocket.sendto(self.msg, (self.ipentry.get(), int(self.portentry.get())))return ‘break’# grate idea!class listenthread(threading.thread):”’tcl/tk multithreading support is needed”’def __init__(self):threading.thread.__init__(self)def run(self):while true:data = mysocket.recv(512)window.msgshow.insert(end, ‘recv: ‘ + data)root = tk()ft = tkfont.font(family=’serif’, size=12, weight=tkfont.normal)root.title(‘udp test’)root.geometry(‘270×350’)window = window(root)mysocket = socket.socket(socket.af_inet, socket.sock_dgram)mysocket.bind((”, int(window.portentry.get())))lt = listenthread()lt.setdaemon(true)lt.start()root.mainloop()
liuxiao216囧gmail.com 原创内容,转载请注明作者,出处。