python线程套接字连接

时间:2015-11-06 09:47:47

标签: python multithreading sockets network-programming

当我尝试创建与多个tcp服务器作为客户端的线程套接字连接时,我遇到了一些问题。

def request(ip, port, packet):
    print "try"
    try: 
        print "create socket..."
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        print "connect..."
        sock.connect((ip, port))
        print "send..."
        sock.send(packet)
        print "recv..."
        d = sock.recv(10240)
        print "parse..."
        resp = parse_response(d)
        sock.close()
        return resp
    except:
        return

def split_list(l, parts):
    newlist = []
    splitsize = 1.0/parts*len(l)
    for i in range(parts):
        newlist.append(l[int(round(i*splitsize)):int(round((i+1)*splitsize))])
    return newlist

def check(hosts):
    for host in hosts:
        host = host.strip().split(":")
        try: 
            request(host[0],host[1], "X")
        except:
            return

def work(list):
    targetlist = split_list(list, 1)
    for ips in targetlist:
        threading.Thread(target=check, args=(ips,)).start()


arr = ["192.168.15.2:99","192.168.15.3:99","192.168.15.4:99","192.168.15.5:99"]

work(arr)

响应如下:

create socket...
connect...
try
create socket...
connect...
try
create socket...
connect...
try
create socket...
connect...

所以问题是,为什么我不能在线程中创建套接字连接?

修改

我已经找到了解决这个问题的更好方法:

< threading.Thread(target=check, args=(ips,)).start()

替换为

  

p =进程(target = check,args =(ips,))   p.daemon =真   p.start()

这将创建一个自己的进程,并且不会像使用线程选项

那样锁定

0 个答案:

没有答案