Python2.7套接字错误37“操作已在进行中”

时间:2018-08-17 19:03:17

标签: python python-2.7 sockets

我正在编写一个脚本,该脚本读取一个充满代理服务器的文件,并检查它们是否正常运行。

import socket

proxyFile = open("proxies.txt","r");
lines = proxyFile.readlines();

class Colors:
    none = "\033[0m";
    red = "\033[31m";
    green = "\033[32m";
    yellow = "\033[33m";
    blue = "\033[34m";
    purple = "\033[35m";
    cyan = "\033[36m";

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
sock.settimeout(3);

for line in lines:
    line = line.replace(":"," : ");
    reader = line.split();
    ip = reader[reader.index(":") - 1];
    port = int(reader[reader.index(":") + 1]);
    try:
        sock.connect((ip,port));
        print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP";
        sock.close();
    except socket.timeout:
        print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN";

似乎文件可以正常读取并创建了套接字,但是它仅连接到一台服务器,然后给出了错误消息。

代理文件:

1.0.134.56:8080
1.165.192.248:3128
1.172.185.143:53281
1.179.156.233:8080
1.179.164.213:8080
1.179.185.253:8080
1.192.242.191:3128
1.20.169.166:8080
1.20.179.68:8080
1.20.99.163:8080

1 个答案:

答案 0 :(得分:1)

您不能重新connect一个套接字。连接后,就可以连接了。即使您致电close

  

以后对套接字对象的所有操作都会失败。

正确的答案是每次通过循环创建一个新的套接字,无论是使用create_connection还是使用socketconnect。例如,将您的try块更改为此:

try:
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
    sock.settimeout(3);
    sock.connect((ip,port));
    print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP";
    sock.close();
except socket.timeout:
    print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN";