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

时间:2016-04-12 22:08:12

标签: python sockets client-server

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

Server.py     导入套接字     导入系统     import _thread

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()

Client1.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)

Client2.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)

0 个答案:

没有答案