我试图用pythonttkinter制作一个聊天程序,但是我的recv函数recvMSG()要么没有接收到任何东西,要么就是不打印任何东西。在
你能帮我解决接收问题吗?你想怎么改就怎么改。在from Tkinter import *
import easygui
import socket
import threading
msgscount = 1
setup = False
def makeServer():
global tcpclisock
host = ''
port = easygui.integerbox(msg='Enter a port...', title='Port', argUpperBound=100000)
buffsize = 1024
addr = (host, port)
setup = True
tcpsersock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsersock.bind(addr)
tcpsersock.listen(5)
tcpclisock, addr = tcpsersock.accept()
easygui.msgbox(msg=('Connected from: ', addr), title='Connected')
def connectServer():
global tcpclisock
setup = True
host = easygui.choicebox(msg='Choose a host...', title='Choose Host', choices=('localhost'),buttons=('Select'))
port = easygui.integerbox(msg='Enter a port...', title='Port', argUpperBound=100000)
buffsize = 1024
addr = (host, port)
tcpclisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpclisock.connect(addr)
def sendMSG():
global msgscount, tcpclisock
try:
msgs.insert(msgscount, ">>" + msg.get())
data = msg.get()
msg.delete(0,END)
msgscount += 1
tcpclisock.send(data)
except:
easygui.msgbox(msg='You need to connect to a server.', title='Error')
def recvMSG():
global msgscount,tcpclisock
if setup == True:
datar = tcpclisock.recv(buffsize)
msgs.insert(msgscount, datar)
msgscount += 1
top.after(1000, recvMSG)
else:
answ = easygui.buttonbox(msg='Please join or create a server', title='Server', choices=("Create", 'Join'))
if answ == "Create":
makeServer()
else:
connectServer()
top = Tk()
top.geometry('640x650')
msgs = Listbox(top, width=105, height=43)
msgs.pack()
msg = Entry(top, bd=2, width=60, font='Arial 12 bold')
msg.pack(side=LEFT)
sendbtn = Button(top, text='Send', font='Arial 15 bold',width=15, padx=5, pady=5,command=runSendMSG)
sendbtn.pack(side=RIGHT)
menubar = Menu(top)
servermenu = Menu(menubar, tearoff=0)
servermenu.add_command(label="Create Server", command=makeServer)
servermenu.add_command(label="Join Server", command=connectServer)
menubar.add_cascade(label='Server', menu=servermenu)
top.config(menu=menubar)
top.after(5000, recvMSG)
mainloop()