如何在Python中使用两次相同的端口

时间:2016-06-29 00:20:57

标签: python sockets networking

即使使用REUSEADDR选项,我仍然无法重用同一组端口。它给了我一个98,"地址已经在使用"错误。

有没有办法在第二组之前杀死第一组套接字,或者修复它?

在下面的代码中,我做了两次相同的事情。

servers = []
port_list = [i for i in range(40007, 40107)]
for port in port_list:
    ds = ('', port)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(ds)
    server.listen(1)
    servers.append(server)

found,_,_ = select.select(servers, [], [])
found = found[0]
conn, addr = found.accept()
print 'Connected by', addr
data = conn.recv(1024)
print "received", data
conn.sendall("message!!")

conn.close()



#time.sleep(10) # even this doesn't work


port_list = [i for i in range(40007, 40107)]
for port in port_list:
    ds = ('', port)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(ds)
    server.listen(1)
    servers.append(server)

found,_,_ = select.select(servers, [], [])
found = found[0]
conn, addr = found.accept()
print 'Connected by', addr

data = conn.recv(1024)
print "received", data
conn.sendall("message!!")

2 个答案:

答案 0 :(得分:3)

您需要在完成服务器套接字后关闭它们。 SO_REUSEADDR不允许您使用打开套接字的地址,只能使用最近已关闭但仍处于TIME_WAIT状态的套接字。

答案 1 :(得分:1)

尝试类似这样的事情 - SO_REUSEPORT vs SO_REUSEADDR并且您将附加到同一服务器列表中。它对你有用吗?

#!/usr/bin/env python
import os
import sys 
import socket
import select

while True:
    servers = []
    port_list = [i for i in range(40007, 40107)]
    for port in port_list:
        ds = ('', port)
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        server.bind(ds)
        server.listen(1)
        servers.append(server)

    f,_,_ = select.select(servers, [], []) 
    for found in f:
        conn, addr = found.accept()
        print 'Connected by', addr
        data = conn.recv(1024)
        print "received", data
        conn.sendall("message!!\n")
        conn.close()


    #time.sleep(10) # even this doesn't work

    servers = []
    port_list = [i for i in range(40007, 40107)]
    for port in port_list:
        ds = ('', port)
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        server.bind(ds)
        server.listen(1)
        servers.append(server)

    f,_,_ = select.select(servers, [], []) 
    for found in f:
        conn, addr = found.accept()
        print 'Connected by -- BB', addr
        data = conn.recv(1024)
        print "received --- BB\n", data
        conn.sendall("message!!----BB\n")
        conn.close()