【问题标题】:How to reuse the socket address python?如何复用socket地址python?
【发布时间】:2018-06-06 02:37:00
【问题描述】:

这是服务器端代码:

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,你是如何到达 s.close() 的?

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


【解决方案1】:

在创建 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?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
相关资源
最近更新 更多