本文整理匯總了Python中socket.SO_REUSEADDR屬性的典型用法代碼示例。如果您正苦於以下問題:Python socket.SO_REUSEADDR屬性的具體用法?Python socket.SO_REUSEADDR怎麽用?Python socket.SO_REUSEADDR使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類socket
的用法示例。
在下文中一共展示了socket.SO_REUSEADDR屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: bind_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
"""Create TCP server socket.
:param host: IPv4, IPv6 or hostname may be specified
:param port: TCP port number
:param backlog: Maximum number of connections to queue
:return: socket.socket object
"""
try: # IP address: family must be specified for IPv6 at least
ip = ip_address(host)
host = str(ip)
sock = socket.socket(
socket.AF_INET6 if ip.version == 6 else socket.AF_INET
)
except ValueError: # Hostname, may become AF_INET or AF_INET6
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(backlog)
return sock
示例2: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def __init__(self, eventHandler):
threading.Thread.__init__(self)
self.name = 'Server'
self.daemon = True
self._eventHandler = eventHandler
self._client = None
self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._server.bind(('', PORT))
self._server.listen(5)
except socket.error:
event = Event(Events.SCAN_ERROR, msg='Could not start server')
post_event(eventHandler, event)
return
self._cancel = False
self.start()
示例3: serve
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def serve(self):
server_socket = None
try:
common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
whereto = (self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport")))
server_socket.bind(whereto)
self.comms_socket = server_socket
self.serverorclient = 1
self.authenticated = False
self.communication_initialization()
self.communication(False)
except KeyboardInterrupt:
self.cleanup()
return
self.cleanup()
return
示例4: acceptThread
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def acceptThread(parameters):
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', int(parameters['listenPort'])))
acceptor.listen(5)
cur_thread = threading.current_thread()
logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')
while True:
(clientSock, clientAddr) = acceptor.accept()
print "==== Output Request ====="
msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
logger.info(msg)
thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
thread3.daemon = True
thread3.start()
acceptor.close()
return
示例5: acceptThread
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def acceptThread():
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', int(uploadPort)))
acceptor.listen(5)
cur_thread=threading.current_thread()
while True:
(clientSock,clientAddr)=acceptor.accept()
print "====Output Request:"
msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
print msg
thread3=threading.Thread(target=sendFile(clientSock))
thread3.daemon=True
thread3.start()
#thread3.join()
acceptor.close()
return
示例6: Create
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
try :
srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except :
raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
try :
srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srvSocket.bind(srvAddr)
srvSocket.listen(srvBacklog)
except :
raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
if not bufSlots :
bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
srvSocket,
srvAddr,
bufSlots )
asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
return xAsyncTCPServer
# ------------------------------------------------------------------------
示例7: start_server
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def start_server(port):
# Start the server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', port))
server_socket.listen(128) # Maximum connections Mac OSX can handle.
status_messages.append(MESSAGE_INFO + "Successfully started the server on port {0}.".format(str(port)))
status_messages.append(MESSAGE_INFO + "Waiting for clients...")
while True:
client_connection, client_address = ssl.wrap_socket(server_socket, cert_reqs=ssl.CERT_NONE, server_side=True, keyfile="server.key", certfile="server.crt").accept()
status_messages.append(MESSAGE_INFO + "New client connected!")
connections.append(client_connection)
示例8: make_socket_proxy
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def make_socket_proxy(ip, port, send_callback=None, recv_callback=None):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('', 8080))
server.listen(1)
t = threading.Thread(
target=listen,
args=(server, ip, port, send_callback, recv_callback)
)
t.start()
sock = socket.create_connection(('localhost', 8080))
sock.settimeout(1)
t.join()
with _socket_lock:
data = _sockets[t.ident]
return (sock, data['lsock'], data['rsock'], server)
示例9: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, source_component=0, use_native=mavutil.default_native):
self._logger = logging.getLogger(__name__)
a = device.split(':')
if len(a) != 2:
self._logger.critical("UDP ports must be specified as host:port")
sys.exit(1)
self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_server = input
self.broadcast = False
self.addresses = set()
if input:
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.port.bind((a[0], int(a[1])))
else:
self.destination_addr = (a[0], int(a[1]))
if broadcast:
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.broadcast = True
mavutil.set_close_on_exec(self.port.fileno())
self.port.setblocking(False)
mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, source_component=source_component, input=input, use_native=use_native)
示例10: test_timeout_empty
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def test_timeout_empty():
# Create a dummy server.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', 5760))
s.listen(1)
try:
# Connect with timeout of 10s.
vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True, heartbeat_timeout=20)
vehicle.close()
# Should not pass
assert False
except:
pass
示例11: _create_ipv4_sockets
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def _create_ipv4_sockets(loopback_enabled):
# Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
mcast_address = "224.0.1.195"
port = 49501
group = (mcast_address, port)
txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if loopback_enabled:
txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
else:
txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
txsock.connect(group)
# Open a multicast receive socket and join the group
rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY)
rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
rxsock.bind(group)
return (txsock, rxsock)
示例12: _create_ipv6_sockets
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def _create_ipv6_sockets(loopback_enabled):
# Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
intf_name = find_ethernet_interface()
intf_index = socket.if_nametoindex(intf_name)
mcast_address = "ff02::abcd:99"
port = 30000
group = (mcast_address, port)
txsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, intf_index)
if loopback_enabled:
txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)
else:
txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
txsock.connect(group)
# Open a multicast receive socket and join the group
rxsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
req = struct.pack("=16si", socket.inet_pton(socket.AF_INET6, mcast_address), intf_index)
if platform.system() == "Darwin":
rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req)
else:
rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_ADD_MEMBERSHIP, req)
rxsock.bind(("::", port))
return (txsock, rxsock)
示例13: build_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def build_socket(self):
"""
Generate either an HTTPS or HTTP socket
"""
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(self.SOCKET_TIMEOUT)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Check if TLS
if self.request_object.protocol == 'https':
self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS)
self.sock.connect(
(self.request_object.dest_addr, self.request_object.port))
except socket.error as msg:
raise errors.TestError(
'Failed to connect to server',
{
'host': self.request_object.dest_addr,
'port': self.request_object.port,
'proto': self.request_object.protocol,
'message': msg,
'function': 'http.HttpUA.build_socket'
})
示例14: run
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def run(self):
try:
logger.info('Starting server on port %d' % self.port)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.hostname, self.port))
self.socket.listen(self.backlog)
while True:
conn, addr = self.socket.accept()
logger.debug('Accepted connection %r at address %r' % (conn, addr))
client = Client(conn, addr)
self.handle(client)
except Exception as e:
logger.exception('Exception while running the server %r' % e)
finally:
logger.info('Closing server socket')
self.socket.close()
示例15: __launch_key_request_process
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SO_REUSEADDR [as 別名]
def __launch_key_request_process(self):
"""
Pick an unused port and start a TCP server. MATLAB will send callback
requests through this socket.
:return: port
"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('localhost', 0))
_, self.key_handler_port = self.sock.getsockname()
self.key_handler_queue = multiprocessing.Queue()
self.key_handler = multiprocessing.Process(
target=self.__key_request_handler,
args=(self.sock,
[self.command_window_id,
self.editor_window_id,
self.vim_window_id],
self.key_handler_queue)
)
self.key_handler.start()
self.key_handler_queue.get(True, 5)
return self.key_handler_port