如何重用套接字地址python?

时间:2017-12-24 06:15:38

标签: python-3.x python-2.7 sockets tcp client-server

这是服务器端代码:

import socket
import sys

HOST = ''   # Symbolic name, meaning all available interfaces
PORT = 7800 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print ('Socket now listening')

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print ('Connected with ' + addr[0] + ':' + str(addr[1]))
    msg = conn.recv(1024)
s.close()

每当我第一次使用此代码时,我可以轻松地与客户端连接,并在第二次出现错误后“通常只允许使用每个套接字地址(协议/网络地址/端口)”

我怎样才能修改一遍又一遍的代码?

1 个答案:

答案 0 :(得分:2)

创建s后尝试此行:

# ...
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ...

Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?