在python中,如何将从所有客户端接收到的消息广播到连接到服务器的所有客户端?

2024-04-26 04:32:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一个聊天服务器客户机程序,其中服务器接收来自多个客户机的消息,然后服务器将它们广播给所有连接到它的客户机。下面的程序向客户端发送消息,但广播代码不工作。请帮忙!!在

在服务器.py 导入套接字 导入系统 导入线程

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
CONNECTION_LIST = []
MESSAGE_LIST = []

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')

#Bind socket to local host and port

s.bind((HOST, PORT))
#Start listening on socket
s.listen(10)
print ('Socket now listening')

def broadcast_data (cl, message):
 for sock in CONNECTION_LIST:
  for msg in MESSAGE_LIST:
   message = MESSAGE_LIST[0]+MESSAGE_LIST[1]
  conn.send(message.encode('ascii'))


#Function for handling connections. This will be used to create threads
def clientthread(conn,addr):
    #Sending message to connected client
    #conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
 while True:

        #Receiving from client
  data = conn.recv(1024)
  data=data.decode('ascii')
  reply = 'Broadcasted message is'+data
  if not data: 
   break
  print("Message received from {0} is:".format(addr))
  print(data)
  MESSAGE_LIST.append(data)
  print(MESSAGE_LIST)
  break
 broadcast_data(CONNECTION_LIST, MESSAGE_LIST)

    #came out of loop



#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    CONNECTION_LIST.append(conn)

    print ('Connected with ' + addr[0] + ':' + str(addr[1]))


    #from threading import Thread
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    _thread.start_new_thread(clientthread ,(conn,addr))

s.close()

客户端1.py

^{pr2}$

客户端2.py

import socket

HOST =socket.gethostname()
PORT = 8888           
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))

text=input('Enter your mesage:') #take message input from user
socket.send(text.encode('ascii'))     #send message to client

bmsg=socket.recv(1024)          #Recieve message from server
bmsg=bmsg.decode('ascii')

print('Message Received from server is:'+bmsg)

Tags: tofrom服务器sendhostmessagedataport