0

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
1
  • i == listening_socket is preferred to i is listening_socket, as the is compares reference not value, which can lead to unexpected results (5 is 5 but not necessarily 123456 is 123456). Commented Dec 26, 2013 at 19:15

1 Answer 1

3

Does this work?

for k in wlist:
    if k != i:
        k.send(data)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!!! I have another question, If I want also to pass a name, so everyone in the chat would be able to see who wrote each message. How can I do it?
Why doesn't each client prepend his/her name to the messages it sends? The server doesn't need to know. If it does need to know, you have a slightly bigger problem, because your server keeps absolutely no data on its clients besides the socket handle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.