[英]I tried to build a simple messenger but the message pops up only when the other user presses Return. How to modify that?
我使用套接字和Tkinter模块构建了一个简单的Messenger。 但是似乎有一个问题。 仅当第一个用户按下Return键发送其消息时,才会显示来自其他用户的消息。 我已尽力解决此问题,但无法解决。
这是我的代码(很抱歉,代码太多,但必须包括所有内容):
Server.py
from Tkinter import *
import socket
host = '127.0.0.1'
port = 5000
s = socket.socket ()
s.bind ((host, port))
s.listen (1)
c, addr = s.accept ()
root = Tk ()
topFrame = Frame (root)
topFrame.pack ()
bottomFrame = Frame (root)
bottomFrame.pack (side = BOTTOM)
scrollBar = Scrollbar (topFrame)
scrollBar.pack (side = RIGHT, fill = Y)
textArea = Listbox (topFrame, width = 40, height = 10, yscrollcommand = scrollBar.set)
textArea.pack (side = LEFT)
scrollBar.config (command = textArea.yview)
enterText = Entry (bottomFrame, width = 30)
textArea.insert (0, "Connection with client established")
def sendText (event):
global c, textArea, enterText
text = enterText.get ()
c.send (text)
textArea.insert (0, "SERVER: " + enterText.get ())
enterText.delete (0, END)
root.update ()
data = c.recv (1024)
textArea.insert (0, "CLIENT: " + str (data))
root.update ()
enterText.pack (side = LEFT, padx = 10, pady = 5)
enterText.bind ('<Return>', sendText)
Send = Button (bottomFrame, text = "Send")
Send.pack (side = RIGHT, padx = 10, pady = 5)
mainloop ()
c.close ()`
客户端
from Tkinter import *
import socket
host = '127.0.0.1'
port = 5002
s = socket.socket ()
s.connect ((host, port))
root = Tk ()
topFrame = Frame (root)
topFrame.pack ()
bottomFrame = Frame (root)
bottomFrame.pack (side = BOTTOM)
scrollBar = Scrollbar (topFrame)
scrollBar.pack (side = RIGHT, fill = Y)
textArea = Listbox (topFrame, width = 40, height = 10, yscrollcommand = scrollBar.set)
textArea.pack (side = LEFT)
scrollBar.config (command = textArea.yview)
enterText = Entry (bottomFrame, width = 30)
textArea.insert (0, "Connection with server established")
def sendText (event):
global s, textArea, enterText
text = enterText.get ()
s.send (text)
textArea.insert (0, "CLIENT: " + enterText.get ())
enterText.delete (0, END)
root.update ()
data = s.recv (1024)
textArea.insert (0, "SERVER: " + str (data))
root.update ()
enterText.pack (side = LEFT, padx = 10, pady = 5)
enterText.bind ('<Return>', sendText)
Send = Button (bottomFrame, text = "Send")
Send.pack (side = RIGHT, padx = 10, pady = 5)
mainloop ()
s.close ()
PS-我只是一个初学者,正在尝试学习
您将recv函数放在sendText中
UI和网络应位于2个不同的线程中。 我建议您多进行一些网络编程,以了解对专用网络线程的需求。
也尝试阅读有关事件队列的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.