Python socket.SOMAXCONN Examples

The following are 12 code examples of socket.SOMAXCONN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: zas_agent.py    From zas_agent with GNU General Public License v2.0 6 votes vote down vote up
def start(self):
        global SCENARIO
        self.logger.debug("listening")
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.bind((self.hostname, self.port))
            self.socket.listen(socket.SOMAXCONN)
        except:
            self.logger.debug("Can not bind to %s:%d"%(self.hostname, self.port))
            sys.exit(0)
        while True:
            conn, address = self.socket.accept()
            self.logger.debug("Got connection")
            process = multiprocessing.Process(target=handle, args=(conn, address, self.scenario, self.args))
            process.daemon = True
            process.start()
            self.logger.debug("Started process %r", process)


##
## Feed the REDIS with pseudo-random stuff
## 
Example #2
Source File: tcp.py    From vanilla with MIT License 6 votes vote down vote up
def listen(self, port=0, host='127.0.0.1'):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((host, port))
        sock.listen(socket.SOMAXCONN)
        sock.setblocking(0)
        port = sock.getsockname()[1]
        server = self.hub.register(sock.fileno(), vanilla.poll.POLLIN)

        @server.pipe
        def server(upstream, downstream):
            for mask in upstream:
                while True:
                    try:
                        conn, host = sock.accept()
                        downstream.send(self.hub.io.socket(conn))
                    except (socket.error, OSError), e:
                        if e.errno == errno.EAGAIN:
                            break
                        raise
            self.hub.unregister(sock.fileno())
            sock.close() 
Example #3
Source File: server.py    From lightsocks with MIT License 6 votes vote down vote up
def listen(self, didListen: typing.Callable=None):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
			listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			listener.setblocking(False)
			listener.bind(self.listenAddr)
			listener.listen(socket.SOMAXCONN)

			logger.info('Listen to %s:%d' % self.listenAddr)
			if didListen:
				didListen(listener.getsockname())

			while True:
				connection, address = await self.loop.sock_accept(listener)
				logger.info('Receive %s:%d', *address)
				asyncio.ensure_future(self.handleConn(connection))

	# 解 SOCKS5 协议
	# https://www.ietf.org/rfc/rfc1928.txt 
Example #4
Source File: test_local.py    From lightsocks with MIT License 6 votes vote down vote up
def setUp(self):
		self.listenAddr = net.Address('127.0.0.1', 1082)
		self.remoteAddr = net.Address('127.0.0.1', 1082)

		self.remoteServer = socket.socket()
		self.remoteServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.remoteServer.bind(self.remoteAddr)
		self.remoteServer.listen(socket.SOMAXCONN)
		self.remoteServer.setblocking(False)

		password = randomPassword()
		self.cipher = Cipher.NewCipher(password)
		self.loop = asyncio.new_event_loop()
		self.local = LsLocal(
			loop=self.loop,
			password=password,
			listenAddr=self.listenAddr,
			remoteAddr=self.remoteAddr)

		self.msg = bytearray(b'hello world')
		self.encrypted_msg = self.msg.copy()
		self.cipher.encode(self.encrypted_msg) 
Example #5
Source File: server.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        Enter the main loop.
        """
        try:
            os.remove(self.address)
        except OSError as err:
            pass

        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.bind(self.address)
        sock.listen(socket.SOMAXCONN)

        self.running = True
        while self.running:
            conn, address = sock.accept()
            try:
                data = conn.recv(MAX_MSG_SIZE)
                request = json.loads(data)
                cmd = request['command']
                if cmd in self.handlers:
                    for callback in self.handlers[cmd]:
                        callback(request)
            except Exception as e:
                print("Caught exception {}".format(e))
                pass
            finally:
                conn.close()

        sock.close()
        os.remove(self.address) 
Example #6
Source File: fake_inet.py    From spacebin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _tcp_server_or_none(port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', port))
        s.listen(socket.SOMAXCONN)
    except Exception as e:
        print "%d/tcp: %s" % (port, str(e))
        return None
    return s 
Example #7
Source File: recipe-577662.py    From code with MIT License 5 votes vote down vote up
def listen(self, backlog = socket.SOMAXCONN):
    self.__socket.listen(backlog) 
Example #8
Source File: tsproxy.py    From tsproxy with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
      self.set_reuse_addr()
      self.bind((host, port))
      self.listen(socket.SOMAXCONN)
      self.ipaddr, self.port = self.socket.getsockname()
      self.current_client_id = 0
    except:
      PrintMessage("Unable to listen on {0}:{1}. Is the port already in use?".format(host, port))
      exit(1) 
Example #9
Source File: local.py    From lightsocks with MIT License 5 votes vote down vote up
def listen(self, didListen: typing.Callable=None):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
			listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			listener.bind(self.listenAddr)
			listener.listen(socket.SOMAXCONN)
			listener.setblocking(False)

			logger.info('Listen to %s:%d' % self.listenAddr)
			if didListen:
				didListen(listener.getsockname())

			while True:
				connection, address = await self.loop.sock_accept(listener)
				logger.info('Receive %s:%d', *address)
				asyncio.ensure_future(self.handleConn(connection)) 
Example #10
Source File: pyvpn.py    From pyvpn with The Unlicense 4 votes vote down vote up
def server_main(gwip, netmask, lip, lport):
    buflen = 65536
    dev, tundev = make_tun()
    print 'Allocated %s' % dev
    tunfd = tundev.fileno()
    logger.info(u'TUN dev OK')
    ifconfig(dev, gwip, netmask)
    enable_tcp_forward()

    sock = socket.socket()
    laddr = (lip, int(lport))
    sock.bind(laddr)
    sock.listen(socket.SOMAXCONN)
    logger.info(u'Sock Listen OK')
    sock.setblocking(False)
    sockfd = sock.fileno()
    clients = {}

    fds = [tunfd, sockfd, ]
    while True:
        try:
            rs, _, _ = select.select(fds, [], [])
        except select.error as e:
            print e
            sys.exit(-1)
        for fd in rs:
            if fd == sockfd:
                cs, ca = sock.accept()
                csfd = cs.fileno()
                fds.append(csfd)
                client = Transport(cs)
                client.set_tunfd(tunfd)
                clients[csfd] = client
                logger.info(u'Remote sock addr: [%s:%d]' % ca)
            elif fd == tunfd:
                logger.info(u'TUN dev recv, rs:[%r]' % rs)
                for client_fd in fds:
                    if client_fd not in [tunfd, sockfd]:
                        os.write(client_fd, os.read(tunfd, buflen))
            else:
                rcv = os.read(fd, buflen)
                if len(rcv) == 0:
                    print u'SOCK rcv [0]'
                    fds.remove(fd)
                    del clients[fd]
                    continue
                logger.info(u'SOCK recv [%d]' % len(rcv))
                client = clients[fd]
                client.recv(rcv) 
Example #11
Source File: daemon.py    From spark-cluster-deployment with Apache License 2.0 4 votes vote down vote up
def manager():
    # Create a new process group to corral our children
    os.setpgid(0, 0)

    # Create a listening socket on the AF_INET loopback interface
    listen_sock = socket.socket(AF_INET, SOCK_STREAM)
    listen_sock.bind(('127.0.0.1', 0))
    listen_sock.listen(max(1024, 2 * POOLSIZE, SOMAXCONN))
    listen_host, listen_port = listen_sock.getsockname()
    write_int(listen_port, sys.stdout)

    # Launch initial worker pool
    for idx in range(POOLSIZE):
        launch_worker(listen_sock)
    listen_sock.close()

    def shutdown():
        global exit_flag
        exit_flag.value = True

    # Gracefully exit on SIGTERM, don't die on SIGHUP
    signal.signal(SIGTERM, lambda signum, frame: shutdown())
    signal.signal(SIGHUP, SIG_IGN)

    # Cleanup zombie children
    def handle_sigchld(*args):
        try:
            pid, status = os.waitpid(0, os.WNOHANG)
            if status != 0 and not should_exit():
                raise RuntimeError("worker crashed: %s, %s" % (pid, status))
        except EnvironmentError as err:
            if err.errno not in (ECHILD, EINTR):
                raise
    signal.signal(SIGCHLD, handle_sigchld)

    # Initialization complete
    sys.stdout.close()
    try:
        while not should_exit():
            try:
                # Spark tells us to exit by closing stdin
                if os.read(0, 512) == '':
                    shutdown()
            except EnvironmentError as err:
                if err.errno != EINTR:
                    shutdown()
                    raise
    finally:
        signal.signal(SIGTERM, SIG_DFL)
        exit_flag.value = True
        # Send SIGHUP to notify workers of shutdown
        os.kill(0, SIGHUP) 
Example #12
Source File: rocket.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self,
                 interfaces=('127.0.0.1', 8000),
                 method='wsgi',
                 app_info=None,
                 min_threads=None,
                 max_threads=None,
                 queue_size=None,
                 timeout=600,
                 handle_signals=True):

        self.handle_signals = handle_signals
        self.startstop_lock = Lock()
        self.timeout = timeout

        if not isinstance(interfaces, list):
            self.interfaces = [interfaces]
        else:
            self.interfaces = interfaces

        if min_threads is None:
            min_threads = DEFAULTS['MIN_THREADS']

        if max_threads is None:
            max_threads = DEFAULTS['MAX_THREADS']

        if not queue_size:
            if hasattr(socket, 'SOMAXCONN'):
                queue_size = socket.SOMAXCONN
            else:
                queue_size = DEFAULTS['LISTEN_QUEUE_SIZE']

        if max_threads and queue_size > max_threads:
            queue_size = max_threads

        if isinstance(app_info, dict):
            app_info['server_software'] = SERVER_SOFTWARE

        self.monitor_queue = Queue()
        self.active_queue = Queue()

        self._threadpool = ThreadPool(get_method(method),
                                      app_info=app_info,
                                      active_queue=self.active_queue,
                                      monitor_queue=self.monitor_queue,
                                      min_threads=min_threads,
                                      max_threads=max_threads)

        # Build our socket listeners
        self.listeners = [Listener(
            i, queue_size, self.active_queue) for i in self.interfaces]
        for ndx in range(len(self.listeners) - 1, 0, -1):
            if not self.listeners[ndx].ready:
                del self.listeners[ndx]

        if not self.listeners:
            log.critical("No interfaces to listen on...closing.")
            sys.exit(1)