amygdalios / pyChat

A simple secure chatting tool made with python and socket
1 stars 1 forks source link

when a client disconnects and reconnects even their own messages will be sent to them #4

Open amygdalios opened 1 month ago

Noveboi commented 3 weeks ago

I assume you are mentioned this behavior: image

The bottom terminal is 'Noveee' and as you can see they receive every message even if it's them sending it. This behavior IS NOT unique to this use case where there user disconnects/reconnects. Here is an example showing that it happens:

image

Based on the way you broadcast message this is the expected behavior for all use cases

# Broadcasting messages to all connected clients
def broadcast(message):
    for client in clients:
        client.send(message)

As you can see the broadcast() function does not have any logic to handle the sending of a message to specific clients. Therefore, every message is sent to everyone. To fix this, we can add extra logic into the broadcast() function to make it 'filter out' any client we want:

Possible implementation No. 1

Add an argument that specifies which clients are to be included in the broadcast.

The argument can be either one socket.socket or many sockets (list[socket.socket])

# Broadcasting messages to all connected clients
def broadcast(message: str, listeners: socket.socket | list[socket.socket]) -> None:
    for client in listeners:
        client.send(message)

Example Use Case:

message = 'Hello World!'
listeners = [client1, client2, client3]
broadcast(message, listeners)

Possible implementation No. 2

Add an argument that specifies which clients are to be excluded in the broadcast

The argument can be either one socket.socket or many sockets (list[socket.socket])

def broadcast(message: str, exclude: socket.socket | list[socket.socket]) -> None:
    listeners = list(set(clients) - set(exclude))
    for client in listeners:
        client.send(message)

Example Use Case:

message = 'Hello World!'
broadcast(message, exclude=[client1, client69])