Python套接字发送数据

时间:2013-12-26 19:08:04

标签: python sockets

我已经开始聊天了。当客户在聊天中写东西时,它会向每个人发送包括他自己在内的消息。我的问题是如何防止从服务器发送他写给他的消息?

这是我的服务器代码:

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 个答案:

答案 0 :(得分:3)

这有用吗?

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