A ZeroMQ socket context that both constructs a socket and closes it.
169570
def _zmq_socket_context(context, socket_type, bind_endpoints):
    """"""
    socket = context.socket(socket_type)
    try:
        for endpoint in bind_endpoints:
            try:
                socket.bind(endpoint)
            except Exception:
                _logger.fatal("Could not bind to '%s'.", endpoint)
                raise
        yield socket
    finally:
        socket.close()
829501
def _CreateZMQSocket(self):
    """"""
    logger.debug('Creating socket for {0:s}'.format(self.name))

    if not self._zmq_context:
      self._zmq_context = zmq.Context()

    # The terminate and close threading events need to be created when the
    # socket is opened. Threading events are unpickleable objects and cannot
    # passed in multiprocessing on Windows.

    if not self._terminate_event:
      self._terminate_event = threading.Event()

    if not self._closed_event:
      self._closed_event = threading.Event()

    if self._zmq_socket:
      logger.debug('Closing old socket for {0:s}'.format(self.name))
      self._zmq_socket.close()
      self._zmq_socket = None

    self._zmq_socket = self._zmq_context.socket(self._SOCKET_TYPE)
    self._SetSocketTimeouts()
    self._SetSocketHighWaterMark()

    if self.port:
      address = '{0:s}:{1:d}'.format(self._SOCKET_ADDRESS, self.port)
      if self.SOCKET_CONNECTION_TYPE == self.SOCKET_CONNECTION_CONNECT:
        self._zmq_socket.connect(address)
        logger.debug('{0:s} connected to {1:s}'.format(self.name, address))
      else:
        self._zmq_socket.bind(address)
        logger.debug(
            '{0:s} bound to specified port {1:s}'.format(self.name, address))
    else:
      self.port = self._zmq_socket.bind_to_random_port(self._SOCKET_ADDRESS)
      logger.debug(
          '{0:s} bound to random port {1:d}'.format(self.name, self.port))
186526
private void close()
    {
        assert (fd != null);

        try {
            fd.close();
            socket.eventClosed(endpoint, fd);
        }
        catch (IOException e) {
            socket.eventCloseFailed(endpoint, ZError.exccode(e));
        }
        fd = null;
    }
534762
def _register_socket(s):
        '''
        
        '''
        queue_to_app = Queue()
        with _lock:
            ApplicationLayer._to_app[s._sockid()] = queue_to_app
        return ApplicationLayer._from_app, queue_to_app
1140007
protected void closeServerSocket() {
        // Close server socket, we do not accept new requests anymore.
        // This also terminates the server thread if blocking on socket.accept.
        if (null != serverSocket) {
            try {
                if (!serverSocket.isClosed()) {
                    serverSocket.close();
                    if (log.isTraceEnabled()) {
                        log.trace("Closed server socket " + serverSocket + "/ref="
                                + Integer.toHexString(System.identityHashCode(serverSocket))
                                + " for " + getName());
                    }
                }
            } catch (IOException e) {
                throw new IllegalStateException("Failed to successfully quit server " + getName(), e);
            }
        }
    }
1088244
public void destroySocket(Socket s)
    {
        if (s == null) {
            return;
        }
        s.setLinger(linger);
        s.close();
        this.sockets.remove(s);
    }
592304
def _bind(self):
        
        if not zmq:
            return
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.PUB)
        self.socket.bind("tcp://*:%i" % self.port)
622962
def closed(self, code, reason=None):
        """"""
        self.emit('socket_closed', code, reason)
        self._recover_network_failure()
909381
def on_close(socket, *data, &block)
      raise UnknownSocket.new(socket) unless @sockets.has_key?(socket)
      raise ArgumentError.new('Block must be supplied') unless block_given?
      raise ArgumentError.new('Block must allow at least one argument') if block.arity == 0
      if(block.arity > 0 && block.arity != (data.size + 1))
        raise ArgumentError.new('Invalid number of arguments for block')
      end
      @sockets[socket][:closed] ||= []
      @sockets[socket][:closed] << [data, block]
    end
709905
def socket_worker(sock, msg_q):
    """"""
    _LOGGER.debug("Starting Socket Thread.")
    while True:
        try:
            data, addr = sock.recvfrom(1024)    # buffer size is 1024 bytes
        except OSError as err:
            _LOGGER.error(err)
        else:
            _LOGGER.debug("received message: %s from %s", data, addr)
            msg_q.put(data)
        time.sleep(0.2)
1343046
@Override
	public void close() {
		boolean enqueueOnSocketContextClose;
		synchronized(closeLock) {
			if(!closed) {
				closed = true;
				enqueueOnSocketContextClose = true;
			} else {
				enqueueOnSocketContextClose = false;
			}
		}
		List<S> socketsToClose;
		synchronized(sockets) {
			// Gets a copy of the sockets to avoid concurrent modification exception and avoid holding lock
			socketsToClose = new ArrayList<>(sockets.values());
			// Each will be removed from socket.close() below: sockets.clear();
		}
		for(S socket : socketsToClose) {
			try {
				socket.close();
			} catch(Exception exc) {
				logger.log(Level.SEVERE, null, exc);
			}
		}
		if(enqueueOnSocketContextClose) {
			Future<?> future = listenerManager.enqueueEvent(
				new ConcurrentListenerManager.Event<SocketContextListener>() {
					@Override
					public Runnable createCall(final SocketContextListener listener) {
						return new Runnable() {
							@Override
							public void run() {
								listener.onSocketContextClose(AbstractSocketContext.this);
							}
						};
					}
				}
			);
			try {
				future.get();
			} catch(ExecutionException e) {
				logger.log(Level.SEVERE, null, e);
			} catch(InterruptedException e) {
				logger.log(Level.SEVERE, null, e);
				// Restore the interrupted status
				Thread.currentThread().interrupt();
			}
		}
		listenerManager.close();
		synchronized(sockets) {
			if(!sockets.isEmpty()) throw new AssertionError("Not all sockets closed");
		}
	}
215150
AmqpClient closeConnection(int replyCode, String replyText, int classId, int methodId1) {
        this.closeConnection(replyCode, replyText, classId, methodId1, null, null);
        return this;
    }
185686
def close(self):
        
        self._socket.close()
        if self._async_socket_cache:
            self._async_socket_cache.close()
            self._async_socket_cache = None
347639
def _handle_socket(self, event: int, fd: int, multi: Any, data: bytes) -> None:
        
        event_map = {
            pycurl.POLL_NONE: ioloop.IOLoop.NONE,
            pycurl.POLL_IN: ioloop.IOLoop.READ,
            pycurl.POLL_OUT: ioloop.IOLoop.WRITE,
            pycurl.POLL_INOUT: ioloop.IOLoop.READ | ioloop.IOLoop.WRITE,
        }
        if event == pycurl.POLL_REMOVE:
            if fd in self._fds:
                self.io_loop.remove_handler(fd)
                del self._fds[fd]
        else:
            ioloop_event = event_map[event]
            # libcurl sometimes closes a socket and then opens a new
            # one using the same FD without giving us a POLL_NONE in
            # between.  This is a problem with the epoll IOLoop,
            # because the kernel can tell when a socket is closed and
            # removes it from the epoll automatically, causing future
            # update_handler calls to fail.  Since we can't tell when
            # this has happened, always use remove and re-add
            # instead of update.
            if fd in self._fds:
                self.io_loop.remove_handler(fd)
            self.io_loop.add_handler(fd, self._handle_events, ioloop_event)
            self._fds[fd] = ioloop_event
710952
def bind(end_point, socket_type):
    
    sock = context.socket(socket_type)
    try:
        sock.bind(end_point)
    except zmq.error.ZMQError as exc:
        sock.close()
        raise exc.__class__('%s: %s' % (exc, end_point))
    return sock
203984
def _close_socket(self):
        
        try:
            self.socket.shutdown(socket.SHUT_RDWR)
        except (OSError, socket.error):
            pass
        self.socket.close()
581677
def close(self):
        
        if self._socket is not None and self._conn is not None:
            message_input = UnityMessage()
            message_input.header.status = 400
            self._communicator_send(message_input.SerializeToString())
        if self._socket is not None:
            self._socket.close()
            self._socket = None
        if self._socket is not None:
            self._conn.close()
            self._conn = None