当前位置: 首页>>代码示例>>Python>>正文


Python socket.bind方法代码示例

本文整理汇总了Python中socket.socket.bind方法的典型用法代码示例。如果您正苦于以下问题:Python socket.bind方法的具体用法?Python socket.bind怎么用?Python socket.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在socket.socket的用法示例。


在下文中一共展示了socket.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_broadcast_sockets

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def create_broadcast_sockets():
    sender = Socket(AF_INET, SOCK_DGRAM)
    sender.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
    sender.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
    sender.bind(("", 0))
    receiver = Socket(AF_INET, SOCK_DGRAM)
    receiver.settimeout(constants.broadcast_receiver_timeout)
    receiver.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
    receiver.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
    receiver.bind(("", constants.broadcast_port))
    return sender, receiver
开发者ID:giflw,项目名称:afn-tools,代码行数:13,代码来源:discovery.py

示例2: Bus

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
class Bus(common.AutoClose):
    """
    An Autobus bus. Busses manage a set of published services, and allow
    connecting to other services. A single bus listens on a single TCP
    port and multiplexes all published services over it.
    
    Bus is a subclass of ServiceProvider; the service it provides is a service
    exposing information about what other services, events, functions, and
    objects are present. (This service is more commonly known as the
    introspection service.) You normally won't have to know this; instances of
    Bus register themselves as services with themselves, so you don't need to
    do anything to make the introspection service work.
    """
    def __init__(self, default_discoverers=True, default_publishers=True,
                 port=None):
        """
        Creates a new bus. The bus will listen on the specified port; if none
        is specified (which is the usual case), a port will be chosen from the
        ports not currently in use on this computer.
        
        If default_discoverers is True (the default), a default set of
        discoverers will be installed, and likewise for default_publishers.
        Right now, this simply installs a autobus2.discovery.BroadcastPublisher
        and autobus2.discovery.BroadcastDiscoverer. Others might be added in
        the future.
        """
        # Number of times this bus has been __enter__'d. Allows it to be used
        # as a re-entrant context manager.
        self.context_enters = 0
        if port is None:
            port = 0
        # True once close() has been called
        self.closed = False
        # The TCP server that will listen for connections
        self.server = Socket()
        self.server.bind(("", port))
        # TODO: make the backlog configurable
        self.server.listen(100)
        self.port = self.server.getsockname()[1]
        # Lock that nearly everything bus-related locks on
        self.lock = RLock()
        # PropertyTable whose keys are service ids and whose values are
        # instances of autobus2.local.LocalService
        self.local_services = PropertyTable()
        self.local_services.global_watch(self.local_service_changed)
        # Map of ids of discovered services to DiscoveredService instances
        self.discovered_services = {}
        self.discovery_listeners = []
        # List of (filter, function) tuples, where filter is an info object
        # filter and function is a function to be notified when a matching
        # service is created or deleted
        self.service_listeners = []
        # Set of RemoteConnection instances that have been bound to a service
        self.bound_connections = set()
        # Set of discoverers registered on this bus
        self.discoverers = set()
        # Set of publishers registered on this bus
        self.publishers = set()
        if default_discoverers:
            self.install_discoverer(discovery.BroadcastDiscoverer())
        if default_publishers:
            self.install_publisher(discovery.BroadcastPublisher())
        Thread(name="autobus2.Bus.accept_loop", target=self.accept_loop).start()
        # Disable the introspection service for now. I'm seeing what would
        # happen if I have per-service introspection functions and objects, so
        # I'm disabling the bus-wide introspection service.
        # self._create_introspection_service()
        #
        # Register the bus as a service on itself.
        self.create_service({"type": "autobus.details", "pid": os.getpid()}, _IntrospectionService(self))
    
    def accept_loop(self):
        """
        Called on a new thread to accept socket connections to this bus.
        """
        self.server.settimeout(1)
        while not self.closed:
            try:
                socket = None
                socket = self.server.accept()[0]
                self.setup_inbound_socket(socket)
            except SocketTimeout: # This happens when we time out, which is
                # normal. The 1-second timeout is to fix what appears to be a
                # bug with Windows not properly throwing an exception from
                # accept when another thread closes the socket.
                pass
            except: # This happens when the server socket is closed
                if socket:
                    socket.close() # Make sure it's /really/ closed on the
                    # off chance that something else caused the exception
                if not issubclass(sys.exc_type, SocketError): # Something else
                    # happened
                    print_exc()
                # print "Bus server died"
                return
    
    @synchronized_on("lock")
    def create_service(self, info, provider):
        """
        Creates a new service on this bus. info is the info object to use for
#.........这里部分代码省略.........
开发者ID:giflw,项目名称:afn-tools,代码行数:103,代码来源:__init__.py

示例3: main

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('--port', '-p', default=8080, type=int,
	                    help='Port to use')
	args = parser.parse_args()

	try:
	    server_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
	    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	    # server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BUFFER_SIZE)

	    server_socket.bind(('', args.port))
	    server_socket.listen(1)

	    cache_dict = {}

	    print "Proxy server ready..."

	    while True:
	    	try:
	    		connection_socket = server_socket.accept()[0]

	    		t = Thread(target=handle_http, args=[cache_dict, connection_socket])
	    		t.setDaemon(1)
	    		t.start()
	    		t.join()
	    	except socket.error, e:
	    		print e
	    	finally:
	    		connection_socket.close()
开发者ID:shenaishiren,项目名称:computer-network-a-top-approach,代码行数:32,代码来源:web-proxy.py

示例4: run_server

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def run_server(server_port):
    """Run the UDP pinger server
    """

    # Create the server socket (to handle UDP requests using ipv4), make sure
    # it is always closed by using with statement.
    server_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)

    # The socket stays connected even after this script ends. So in order
    # to allow the immediate reuse of the socket (so that we can kill and
    # re-run the server while debugging) we set the following option. This
    # is potentially dangerous in real code: in rare cases you may get junk
    # data arriving at the socket.
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Set the server port
    server_socket.bind(("", server_port))

    # Start accepting ping requests
    print ("Ping server ready on port", server_port)
    while True:
        # Receive message and send one back
        _, client_address = server_socket.recvfrom(1024)
        server_socket.sendto("Pong".encode(), client_address)

    return 0
开发者ID:rodrigoncalves,项目名称:myhttpd,代码行数:28,代码来源:ping.py

示例5: main

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def main():
    register_builtin_interface()
    server = Socket()
    if len(sys.argv) > 1:
        server_port = int(sys.argv[1])
    else:
        server_port = DEFAULT_PORT
    print "Listening on port " + str(server_port)
    server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    server.bind(("", server_port))
    server.listen(50)
    
    Thread(target=process_event_queue).start()
    
    print "\nAutobus has successfully started up."
    
    try:
        while True:
            socket, address = server.accept()
            connection = Connection(socket, address)
            event_queue.put((connection.id, discard_args(connection.register)), block=True)
            connection.start()
    except KeyboardInterrupt:
        print "KeyboardInterrupt received, shutting down"
        event_queue.put((None, None), block=True)
        print "Event queue has been notified to shut down"
    except:
        print "Unexpected exception occurred in the main loop, shutting down. Stack trace:"
        print_exc()
        event_queue.put((None, None), block=True)
        print "Event queue has been notified to shut down"
    server.close()
开发者ID:giflw,项目名称:afn-tools,代码行数:34,代码来源:__init__.py

示例6: listen

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
 def listen(self):
     """
     Bind and listen.
     :return: The open socket.
     :rtype: socket.socket
     """
     address = (self.host, self.port)
     socket = Socket(AF_INET, SOCK_STREAM)
     socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
     socket.bind(address)
     socket.listen(5)
     log.info('listening on: %d', self.port)
     return socket
开发者ID:darinlively,项目名称:gofer,代码行数:15,代码来源:manager.py

示例7: __init__

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
 def __init__(self):
     # Set up the interrupt socket
     interrupt_server = Socket()
     interrupt_server.bind(("localhost", 0))
     interrupt_server.listen(1)
     self.interrupt_writer = Socket()
     self.interrupt_writer.setblocking(False)
     self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1])
     self.interrupt_reader = interrupt_server.accept()
     interrupt_server.shutdown(SHUT_RDWR)
     interrupt_server.close()
     self.interrupt_reader.setblocking(False)
     self.interrupt_writer.setblocking(False)
开发者ID:giflw,项目名称:afn-tools,代码行数:15,代码来源:net.py

示例8: listen_for_data

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def listen_for_data(sock: socket.socket) -> None:
    """Make the socket listen for data forever."""
    host = 'localhost'
    port = 41401
    sock.bind((host, port))
    sock.listen(1)
    while True:
        print('Waiting...')
        conn, addr = sock.accept()
        print(f'Connection from {addr}')
        if addr[0] != '127.0.0.1':
            continue
        with conn:
            data = receive_all(conn)
            parse_data(data)
开发者ID:hyshka,项目名称:dotfiles,代码行数:17,代码来源:pyclip.py

示例9: run_server

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def run_server(server_port):
	# Run UDP pinger server

	try:
		server_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

		server_socket.bind(('', server_port))

		print("Ping server ready on port", server_port)
		while True:
			_, client_address = server_socket.recvfrom(1024)
			server_socket.sendto("".encode(), client_address)
	finally:
		server_socket.close()

	return 0
开发者ID:shenaishiren,项目名称:computer-network-a-top-approach,代码行数:19,代码来源:ping.py

示例10: SocketStream

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
class SocketStream(Stream):
    def __init__(self, port):
        self.listener = Socket(AF_INET, SOCK_STREAM)
        self.listener.bind(('', port))

    def open(self):
        self.listener.listen(1)
        self.socket, address = self.listener.accept()

    def read(self, size=1024):
        return self.socket.recv(size)

    def write(self, data):
        self.socket.sendall(data)

    def close(self):
        self.socket.close()
        self.listener.close()
开发者ID:hezymal,项目名称:drive-away,代码行数:20,代码来源:main.py

示例11: main

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def main():
	parser=argparse.ArgumentParser()
	parser.add_argument('--port','-p',default=2000,type=int,help='port to use')
	args=parser.parse_args()
	server_socket=Socket(socket.AF_INET,socket.SOCK_STREAM)
	server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
	server_socket.bind(('',args.port))
	server_socket.listen(1)
	print "server running"
	while True:
		connection_socket=server_socket.accept()[0]
		request=connection_socket.recv(1024)
		reply=http_handler(request)
		connection_socket.send("HTTP/1.1 200 OK\n") 
		connection_socket.send("\n")

		connection_socket.send(reply)
		connection_socket.close()

		print "received request"
		print "reply sent"

	return 0
开发者ID:p1p13,项目名称:Computer-Networking-A-Top-Down-Approach,代码行数:25,代码来源:webserver.py

示例12: bind_reuse

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def bind_reuse(ip, port):
    sock = Socket()
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sock.bind((ip, port))
    return sock
开发者ID:jolynch,项目名称:pip-faster,代码行数:7,代码来源:ephemeral_port_test.py

示例13: bind_naive

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
def bind_naive(ip, port):
    sock = Socket()
    try:
        sock.bind((ip, port))
    except socket.error as error:
        return error
开发者ID:jolynch,项目名称:pip-faster,代码行数:8,代码来源:ephemeral_port_test.py

示例14: wait_connect

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
    def wait_connect(self):
        if self.needQuit:
            return
        self.init_graphic()
        self.informBoard = dashboard.InformBoard((10, 25), 15)

        test = 0
        server = Socket(socket.AF_INET, socket.SOCK_STREAM)
        if not test:
            while 1:
                try:
                    server.bind(("", config.Port))
                    break
                except socket.error as e:
                    self.inform(str(e))
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            self.quit()
                            break
                    self.render_connection()
                    sleep(1)
            server.listen(2)
            server.settimeout(0.0)

            player1 = Player(1, server)
        else:
            player1 = HumanPlayer(1)

        if self.add_human:
            player2 = HumanPlayer(2)
            # add handler for human player
            self.pyeventHandlers.append(player2)
        else:
            player2 = Player(2, server)

        players = [player1, player2, None]

        timer = pygame.time.Clock()
        # wait until connected 2 players
        finished = 0
        player = players[finished]
        try:
            self.inform("waiting for AI to connect...")
            while finished < 2:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        self.quit()
                        break
                if self.needQuit:
                    break
                if player.connect():
                    self.add_player(player)
                    self.inform("AI %s connected" % (player.name))
                    finished += 1
                    player = players[finished]
                self.render_connection()
                timer.tick(10)
        except KeyboardInterrupt:
            server.close()
            return False
        server.close()

        return True
开发者ID:ZhanruiLiang,项目名称:MSRA-Python-Clone,代码行数:65,代码来源:shippo.py

示例15: Socket

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import bind [as 别名]
import socket as Net
from socket import socket as Socket
import os,re,sys

print Net.AF_INET,Net.SOCK_STREAM
s = Socket(Net.AF_INET,Net.SOCK_STREAM)

#get localhost name and ip address
localhostName = Net.gethostname()
localhostAddress = Net.gethostbyname(localhostName)
print localhostName , localhostAddress

try:
    s.bind((localhostAddress,10010))
    print 'bind succeed!'

    s.listen(10)
    print 'start to listen!'
except Exception as ex:
    print 'Error' , ex
finally:
    s.close()
    print 'socket closed!'
开发者ID:xp880906,项目名称:Python-Demos,代码行数:25,代码来源:pySocketDemo.py


注:本文中的socket.socket.bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。