试图用Python编写聊天应用程序,但由于某些原因我不知道,当第一个客户端发送数据时,它可以工作,但第二个或其他客户端无法接收它直到其他客户端尝试发送消息,它工作正常......
这是我的客户代码:
from Tkinter import *
from PIL import ImageTk, Image
from socket import *
from threading import Thread, Lock
import time
'#Connect to Server'
shutdown = False
host = "127.0.0.1"
port = 0
server = ("127.0.0.1", 12345)
s = socket(AF_INET, SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
global alias
def sendmsg():
msg = alias + " : " + chatEntry.get("0.0", END).strip() + "\n"
#chatLog.config(state=NORMAL)
#chatLog.insert(END, msg)
chatEntry.delete(1.0, END)
#chatLog.config(state=DISABLED)
s.sendto(msg, server)
def recvmsg(name, sock):
while not shutdown:
try:
while True:
data = sock.recv(1024)
chatLog.config(state=NORMAL)
chatLog.insert(END, str(data))
chatLog.config(state=DISABLED)
print str(data)
except:
pass
alias = raw_input("Alias ==> ")
root = Tk()
'#Create a window'
frame = Frame(root, width=600, height=450, bg="black")
frame.pack()
'#Create a chat log'
chatLog = Text(root, font=("Determination Sans", 12))
chatLog.insert(END, "Connecting..... \n")
chatLog.config(state=DISABLED)
chatLog.place(x=13, y=13, width=425, height=329)
'#Create list of friends online'
friendsList = Text(root)
friendsList.config(state=DISABLED)
friendsList.place(x=445, y=13, width=142, height=329)
'#Create an entry where you can enter your message'
chatEntry = Text(root)
chatEntry.place(x=13, y=349, width=425, height=96)
'#Create a send button'
btnLogin = Button(root, text="SEND", command=sendmsg)
btnLogin.place(x=445, y=349, width=142, height=96)
'#Set it fixed, not resizable......'
root.resizable(width=FALSE, height=FALSE)
root.wm_title("Chat - Underchat")
Thread(target=recvmsg, args=("RecvThread", s)).start()
root.mainloop()
这是我的服务器代码:
from socket import *
import time
'#Put IP here...'
'#Put Socket here...'
host = "127.0.0.1"
port = 12345
clients = []
s = socket(AF_INET, SOCK_DGRAM)
s.bind((host, port))
'#Set Blocking to 0 so it will accept basically everything'
s.setblocking(0)
quitting = False
print "server started....."
while not quitting:
try:
'#Receive 1024 bytes of data... Its basically 1KB :P '
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
'#Quit if a specified string was detected...'
quitting = True
if addr not in clients:
'#If a new client was found, add them to the clients list'
clients.append(addr)
print time.ctime(time.time()) + str(addr) + ": :" + str(data)
for client in clients:
'#Send the data to all clients... This is a groupchat afterall :3'
s.sendto(data, client)
except:
'#Try again if something goes wrong.....'
pass
'#Close the connection when out of the loop'
s.close()
那么任何想法?感谢