0

To learn socket programming, i thought what better way to learn that write a chatroom. Client sends data to server, server re-transmits that data to rest of the clients (except for the client the data came from).

server.py (for now just prints data sent from client)

def new_client(c, addr):
    # Initialize client. Receive display name from client, give client random uid
    client_name = c.recv(1024).decode()
    uid = random.randint(0, 10)             #TODO duplicate uid is not wanted
    c.send(pickle.dumps(uid))

    while True:
        data = unpickle_msg(c.recv(1024))
        print(f"{client_name} ({addr[0]}:{addr[1]}) >>> {data[1]}")


while True:
    client_conn, addr = s.accept()
    print(f"Connection from {addr}")
    t = threading.Thread(target=new_client, args=[client_conn, addr])
    t.start()

client.py:

def read_send_data():
    while True:
        msg = pickle_msg(input(">>> "))
        s.send(msg)
read_send_data()

Problem: In the while loop in new_client(), i want to re-transmit the data to other clients but each and every client to server connection will be in its own thread. What are some ways to approach this?

  • 1
    You will need to keep track of active threads by keeping them in a list or dict or some other appropriate object for you problem. You can assign a thread-safe input [queue](https://docs.python.org/3/library/queue.html#module-queue) to each thread. This is just one technique. Your socket receiving code appears to make the common mistake of assuming that TCP data is delivered in packets or "messages". This is not so. Please read and understand [this answer](https://stackoverflow.com/a/41383398/238704) to correct this. – President James K. Polk Jul 31 '21 at 18:09
  • @PresidentJamesK.Polk Can you provide some good resources/reads for understanding and using threading? – lizardowl5151 Aug 01 '21 at 23:55

0 Answers0