0
我不知道如何讓有多人連接到我的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()
可能不是一個好主意,發佈您的真實IP地址。 –