Nityuiop18
Nityuiop18

Reputation: 113

Python socket send data

I have started working on a chat. When a client writes something in the chat its sends everyone his message including himself. My question is how to prevent sending the message he wrote to him from the server?

This is my server code:

listening_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
listening_socket.bind( ("", 1234) )
listening_socket.listen(5)
open_sockets = []

while True:
    rlist, wlist, xlist = select.select([listening_socket] + open_sockets,
                                        [listening_socket] + open_sockets,
                                        [])
    for i in rlist:
        if i is listening_socket:
            new_socket, addr = listening_socket.accept()
            open_sockets.append(new_socket)
        else:
            data = i.recv(1024)
            if data == "":
                open_sockets.remove(i)
                print "Connection closed"
            else:
                print repr(data)
                for k in wlist:
                    k.send(data)  # <==== here it sends the message to every one

Upvotes: 0

Views: 1213

Answers (1)

salezica
salezica

Reputation: 76889

Does this work?

for k in wlist:
    if k != i:
        k.send(data)

Upvotes: 3

Related Questions