我不知道怎么说当有多个人连接到我的python服务器时能够输入一条消息并立即看到它而没有其他人需要按回车才能看到它。我如何在这里使用线程?
服务器:
import socket, thread
def reactor(sock,client,data):
try:
sock.sendto(data.encode('utf-8'),client)
sock.close()
except Exception,e :
print(e)
sock.close()
def Main():
host = '25.4.221.63'
port = 5000
clients = []
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((host,port))
print("Server Started")
while True:
data,addr=s.recvfrom(1024)
if addr not in clients:
clients.append(addr)
data = data.decode('utf-8')
print("Message From: " + str(addr))
print("From connected user: " + data)
print("Sending: " + data)
for client in clients:
try:
thread.start_new_thread(reactor,(s,client,data))
except Exception,e :
print(e)
s.close()
if __name__ == '__main__':
Main()
客户端:
import socket
def Main():
alias = input("ScreenName:")
inp = input("IP:")
host =inp
port = 5001
server = ('25.4.221.63',5000)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((host,port))
message = input("-> ")
while message != 'q':
s.sendto(message.encode('utf-8'), server)
data,addr = s.recvfrom(1024)
data = data.decode('utf-8')
print(data)
message = input(alias + ' -> ')
s.close()
if __name__ == '__main__':
Main()
答案 0 :(得分:0)
避免线程;使用select
。
您应该使用select
或epoll
同时等待来自套接字或标准输入的输入。如果select
表示套接字已准备好阅读,请阅读您的消息。如果stdin已准备好读取,请阅读用户输入。这需要自己实施input
。