我试图在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()
答案 0 :(得分:1)
如果我没弄错,我会说receiveloop方法接受self元素,但只需要类所需的self参数,而且这个方法不在类中
试试这个:
#Loop for receiving
def receivingloop():
global fromserver
while 1:
fromserver = s.recv(30)
time.sleep(.5)
答案 1 :(得分:0)
你的函数是用一个名为'self'的变量定义的,看起来你以前在一个类中有这个函数,但后来决定从类中提取它。
无论如何,为了解决你的问题,它应该是:
def receivingloop():
请注意,函数参数中的“self”部分已被删除。
此外,您可能希望将global data
添加到发送功能。