如何将广播数据发送到多线程套接字服务器中的所有客户端?

时间:2018-01-01 23:29:03

标签: python multithreading sockets chatroom

我目前正在使用python创建多线程聊天室,但是我无法向所有客户端广播数据。

我希望创建一个系统,其中一个客户端将数据发送到服务器,服务器将数据广播到其他客户端。

我希望实现的目标:      https://i.stack.imgur.com/uvG54.png

服务器:

x = xrange(2011, 2015)
y = xrange(2012, 2016)
z = ['%5d / %5d' % (a, b) for a,b in zip(x,y)] 
print '\n'.join(z)

客户端:

import socket
import threading
import sys
import time

USERNAME = str(input("Enter your username: "))
MAX_CLIENTS = int(input("How many clients: "))
BUFF_SIZE = 1024
HOST = ''
PORT = 9999

lock = threading.Lock()

class Server:
    def __init__(self):
        self.clients = [] #list of clients
        self.messages = [] #messages
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = HOST
        self.port = PORT
        self.sock.bind((self.host, self.port))
        threading.Thread(self.listener()).start()
    def conn_handler(self, conn):
        while True:
            with lock:
                self.data = conn.recv(BUFF_SIZE).decode("utf-8")
                print(data)
                self.messages.append(self.data)
                conn.sendall(self.data.encode("utf-8")) #error occurs here, cannot send data to all clients
                time.sleep(.01)
    def listener(self):
        for x in range(MAX_CLIENTS):
            self.sock.listen(1)
            conn, addr = self.sock.accept()
            print("{} has connected!".format(addr))
            self.clients.append(addr)
            threading.Thread(target=self.clientthread, args=(conn,)).start()
            threading.Thread(target=self.conn_handler, args=(conn,)).start()

server = Server()

0 个答案:

没有答案