我一直在試圖通過我的局域網上的TCP python服務器,但我一直遇到這個項目的問題。我的問題是:是否可以從一臺服務器向多個客戶端發送消息(通過TCP)? (即,客戶端-1發送消息「Hello world」,並且它在所有其他客戶端[客戶端-2,客戶端-3]上顯示消息)。我的繼承人服務器到目前爲止的代碼:Python的TCP服務器發送消息到所有的客戶端
import socket, time, sys
import threading
TCP_IP = input("Host IP: ")
TCP_PORT = int(input("Host Port: "))
BUFFER_SIZE = 1024
def createNewThread(function):
threading.Thread(target=function).start()
def Listening():
try:
while True:
s.listen(1)
conn,addr = s.accept()
threading.Thread(target=Listening).start()
print("User joined with IP %s" % (addr[0]))
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
conn.send(addr[0].encode("utf-8") + b': ' + data)
conn.close()
except ConnectionResetError as e:
print("Connection was closed: ", e)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
print("-----Server started-----")
Listening()
except socket.error as e:
print("Socket error occured. More info: ", e)
而且繼承人我的代碼客戶端:
import socket, sys, time
TCP_IP = input("Connect to Local IP: ")
TCP_PORT = int(input("Connect to Local Port: "))
BUFFER_SIZE = 1024
running = True
while running == True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting...")
s.connect((TCP_IP,TCP_PORT))
print("Connected!")
while True:
MESSAGE = input("Message: ")
if MESSAGE == "exit":
s.close()
raise SystemExit
s.send(MESSAGE.encode('ascii'))
data = s.recv(BUFFER_SIZE)
print(data.decode("utf-8"))
running = False
time.sleep(20)
except:
print(sys.exc_info()[0])
time.sleep(1)
在此先感謝任何答案!
編輯: 我想要的輸出中看起來是這樣的:
User3's IP: Message they sent
User1's IP: Message they sent
Message: What do you want to send?
「是否可以通過TCP發送消息給多個客戶端?」 - 是的。你面臨的問題是什麼? – Prabhu
@Prabhu *嘆*如何? –