【问题标题】:python socket tcp send to someonepython socket tcp 发送给某人
【发布时间】:2018-01-31 11:30:34
【问题描述】:

我启动了一个套接字 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)方法。

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

那么我该怎么做呢?谢谢。

【问题讨论】:

  • 如果你从服务器和客户端放一个完整的代码狙击会很好,我不是在谈论真实的东西,而是对它的简化
  • @gsi-frank 现在怎么样?
  • 大量样板代码使我们想要帮助您的工作太多,以至于无法理解问题。你能想出与问题相关的代码吗?:客户端套接字、服务器套接字和通用数据传输代码,不包括你的脚本细节,代码是什么乱七八糟的。
  • 很难从所提供的细节中回答。 sendto 的文档指出不应连接套接字,但是我怀疑在您的代码中它给出了 socket = self.request 行。

标签: python sockets tcp


【解决方案1】:

如果你展示了代码的客户端会有点帮助,但是我会尽力帮助你。

以下是我从你的问题中解释的:

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)

【讨论】:

  • 如果您想从特定端口发送单个数据包怎么办。但不是其他数据包。有什么办法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多