0
votes

I started a socket tcp server and two socket clients

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

I recoded every clients when they connected to the socket

then socket tcp server use socket.sendto(string[,flag],address) method.

but why the both of clients received the data. I just want send to someone.

So how can I do this? thank you.

1
Would be nice if you put a complete code snipe from the server and client, I'm not talking about the real thing but of a simplification of it - user1785721
@gsi-frank how about now? - Cheng Jeiry
A lot of boilerplate code that makes us who want to help you work too much to just understand the problem. Could you just come up with the code relevant to the problem?: client socket, server socket, and generic data transfer code, excluding the specifics of your script, what clutter the code. - user1785721
Hard to answer from the details provided. The documentation for sendto states the socket should not be connected however I suspect in your code it is given the socket = self.request line. - FujiApple

1 Answers

3
votes

It would have been a little helpful if you showed the client side of the code, however I will try my best to help you.

The following is what I interpreted from your question:

The method socketobj.sendto(data, (host, port)) is actually paired with the method socketobj.recvfrom(BUFFER_SIZE), which is only used in udp(user datagram protocol) networking in Python. To send data using the tcp protocol you must do the following:

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)