python socket tcp发送给某人

时间:2017-08-23 03:27:46

标签: python sockets tcp

我启动了套接字tcp服务器和两个套接字客户端

def loopRedis(self):
    socket = self.request
    while True:
        for key in r.scan_iter(match='push:*', count=100000):
#            print key
            ##find the msg that I need to push
            data = json.loads(r.get(key))
            ##get the userid from push:*
            flag = False
            for userKey in r.scan_iter(match='redis:*', count=100000):
                if flag == False:
                    if r.hget(userKey,'userid') == data['userid']:
                        print '======='
                        print r.hget(userKey,'ip')
                        print int(r.hget(userKey,'id'))
                        print '|||||||||'
                        #find the map(ip and id and userid)from redis:*
                        socket.sendto(prpcrypt().encrypt(r.get(key)), (r.hget(userKey,'ip'),int(r.hget(userKey,'id'))))
                        flag = True
    #                    r.delete(key)  ##delete when I send
            time.sleep(2) ## looping

我在连接到套接字时重新编码每个客户端

然后socket tcp服务器使用socket.sendto(string [,flag],address)方法。

但是为什么两个客户都收到了数据。我只想发送给某人。

那我该怎么做呢?谢谢。

1 个答案:

答案 0 :(得分:2)

如果您展示了代码的客户端,那将会有所帮助,但我会尽力帮助您。

以下是我从您的问题中解释的内容:

方法socketobj.sendto(data, (host, port))实际上与方法socketobj.recvfrom(BUFFER_SIZE)配对,方法仅用于Python中的udp(用户数据报协议)网络。要使用tcp协议发送数据,您必须执行以下操作:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = xxx.xxx.xxx.x #whatever ip
port = x #whatever port (make sure it is the same for the client in tcp)
s.bind((host, port))
clients = [] #clients use the clients.append(whatever_to_add_to_list) method to add clients
for client in clients: #for loop to iterate through the client list
    client.connection.send(data)