我正在尝试在 python 中创建一个简单的“聊天”客户端。我有基础知识和一切,但我根本无法让我的线程工作。这仍然是一项正在进行的工作,因此并非所有代码都在那里,我知道,但是如果您确实有任何整体建议,将不胜感激。
from Tkinter import *
import time
import socket
import thread
import threading
HOST = 'localhost'
PORT = 5454
fromserver = ''
data = ''
#Declares socket information
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((HOST,PORT))
#Loop for receiving
def receivingloop():
global fromserver
while 1:
fromserver = s.recv(30)
time.sleep(.5)
class ChatClient:
def __init__(self, master):
#Use Global fromserver
global fromserver
global data
#Create both frames
top_frame = Frame(master)
bot_frame = Frame(master)
#Create and pack the Buttons
self.send_but = Button(bot_frame, \
text='Send',\
command=self.sending)
self.quit_but = Button(bot_frame, \
text='Quit', \
command=client_window.destroy)
self.send_but.pack(side=LEFT)
self.quit_but.pack(side=LEFT)
#Create and pack label
self.received_lab = Label(top_frame,\
text=(fromserver))
self.received_lab.pack()
self.sent_lab = Label(top_frame,\
text='Message Sent: ' +data)
self.sent_lab.pack()
self.sending_entry = Entry(top_frame, \
width=10)
self.sending_entry.pack()
#Pack Frames
top_frame.pack()
bot_frame.pack()
#Function to send stuff
def sending(self):
global data
s.sendto(data,(HOST,PORT))
data = str(self.sending_entry.get())
print data
#Start the thread
l1 = threading.Thread(target=receivingloop)
l1.start()
client_window = Tk()
chat_client = ChatClient(client_window)
client_window.mainloop()