Open Handler Socket

@throwsHSrException
340574
public function open()
    {
        $this->socket = stream_socket_client('tcp://'.$this->address, $errc, $errs, STREAM_CLIENT_CONNECT);

        if (!$this->socket) {
            throw new HSException('Connection to '.$this->address.' failed');
        }
    }
298496
@Override
    public void handleTransportError(final WebSocketSession webSocketSession, final Throwable exception) throws Exception {
        if (exception != null) {
            logger.error("[handleTransportError]", exception);
        }
    }
76203
public void bindAndStart(int port) throws Exception {
        server = new NioServer(new StreamConnectionFactory() {
            @Override
            public ProtobufConnection<Protos.TwoWayChannelMessage> getNewConnection(InetAddress inetAddress, int port) {
                return new ServerHandler(new InetSocketAddress(inetAddress, port), timeoutSeconds).socketProtobufHandler;
            }
        }, new InetSocketAddress(port));
        server.startAsync();
        server.awaitRunning();
    }
685171
@Override
    public Object handle(Message msg) throws Exception {
        if(req_handler != null)
            return req_handler.handle(msg);
        return null;
    }
33162
private WebSocketOutputStream openOutputStream(Socket socket) throws WebSocketException
    {
        try
        {
            // Get the output stream of the socket through which
            // this client sends data to the server.
            return new WebSocketOutputStream(
                new BufferedOutputStream(socket.getOutputStream()));
        }
        catch (IOException e)
        {
            // Failed to get the output stream from the raw socket.
            throw new WebSocketException(
                WebSocketError.SOCKET_OUTPUT_STREAM_FAILURE,
                "Failed to get the output stream from the raw socket: " + e.getMessage(), e);
        }
    }
872043
private void fireSocketClosedEvent(final Exception listenerException) {
    synchronized (listenerList) {
        for (Iterator iter = listenerList.iterator(); iter.hasNext();) {
            SocketNodeEventListener snel =
                    (SocketNodeEventListener) iter.next();
            if (snel != null) {
                snel.socketClosedEvent(listenerException);
            }
        }
    }
  }
464412
@Nonnull
  public final HandlerRegistration addOpenHandler( @Nonnull final OpenEvent.Handler handler )
  {
    return _eventBus.addHandler( OpenEvent.getType(), handler );
  }
1169973
function OpenEventObserver(clientPort, serverPort) {
    events.EventEmitter.call(this);

    this.isClientPortOpen = false;
    this.isServerPortOpen = false;

    clientPort.on('open', this._clientPortOpenHandler(this));
    serverPort.on('open', this._serverPortOpenHandler(this));
}
1129900
@Override
    public ReadStream<Buffer> handler(Handler<Buffer> handler) {
        if (handler == null) {
            throw new IllegalArgumentException("handler");
        }
        this.dataHandler = handler;
        doRead();
        return this;
    }
1097662
protected HttpURLConnection openConnection(String url, Map<String, String> header) throws IOException {
		// Initialize connection
		URL urlObj = null;
		HttpURLConnection conn = null;

		int redirectCount = 0;
		boolean redirect = true;
		while (redirect) {
			if (redirectCount > 10) {
				throw new ProtocolException("Too many redirects: " + redirectCount);
			}

			if (conn == null) {
				urlObj = new URL(url);
			} else {
				// get redirect url from "location" header field
				urlObj = new URL(conn.getHeaderField("Location"));
			}

			// open the new connection again
			conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod(header.get("method"));
			conn.setInstanceFollowRedirects(true);

			// Set output if PUT or POST
			if (conn.getRequestMethod() == "POST" || conn.getRequestMethod() == "PUT") {
				conn.setDoOutput(true);
			}

			// Set request header
			for (Map.Entry<String, String> headerAttr : header.entrySet()) {
				conn.addRequestProperty(headerAttr.getKey(), headerAttr.getValue());
			}

			// Check if redirect
			redirect = false;
			if (conn.getRequestMethod() == "GET") {
				int status = conn.getResponseCode();
				if (status != HttpURLConnection.HTTP_OK) {
					if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
						redirect = true;
					redirectCount++;
				}
			}
		}

		return conn;
	}
415333
@Override
    public void handleRequest(HttpInboundConnection hic, HttpServletRequest request, HttpServletResponse response) {
        Http2InboundConnection h2ic = (Http2InboundConnection) hic;
        H2UpgradeHandlerWrapper h2uh = null;
        try {
            h2uh = request.upgrade(H2UpgradeHandlerWrapper.class);
        } catch (IOException e) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning: user configurator threw an IOException. Exception message: " + e.getMessage());
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;

        } catch (ServletException e) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning: user configurator threw a ServletException. Exception message: " + e.getMessage());
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        if (h2uh != null) {
            h2uh.init(new H2UpgradeHandler());
        }
        
        // create a map of the headers to pass to the transport code
        Map<String, String> headers = new HashMap<String, String>();
        HttpServletRequest hsrt = (HttpServletRequest) request;
        Enumeration<String> headerNames = hsrt.getHeaderNames();
        
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = hsrt.getHeader(key);
            headers.put(key, value);
        }
        boolean upgraded = h2ic.handleHTTP2UpgradeRequest(headers);
        if (!upgraded) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning: http2 connection initialization failed");
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
1146555
@Override
  public void open() throws NetworkException {

    LOG.log(Level.FINE, "looking up {0}", this.destId);

    try {
      // naming lookup
      final InetSocketAddress addr = this.service.getNameClient().lookup(this.destId);
      if (addr == null) {
        final NetworkException ex = new NamingException("Cannot resolve " + this.destId);
        LOG.log(Level.WARNING, "Cannot resolve " + this.destId, ex);
        throw ex;
      }

      LOG.log(Level.FINE, "Resolved {0} to {1}", new Object[]{this.destId, addr});

      // connect to a remote address
      this.link = this.service.getTransport().open(addr, this.codec, this.listener);
      LOG.log(Level.FINE, "Transport returned a link {0}", this.link);

    } catch (final Exception ex) {
      LOG.log(Level.WARNING, "Could not open " + this.destId, ex);
      throw new NetworkException(ex);
    }
  }
973854
protected void handleClient(final Socket client) throws IOException {
		final ClientHandler handler = new ClientHandler(client);
		this.executorService.execute(handler);
	}
1275232
public function open()
    {

        $this->log('open socket connection');
        $this->socket = fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
        if ($this->socket) {
            socket_set_blocking($this->socket, 1);

            return true;
        } else {
            throw(new \Exception("{$errstr} (#{$errno})"));
        }
    }
539989
@Override
	public void run() {
		stopped = false;
		try {
			try {
				serverSocket = new ServerSocket(port);
				serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5 seconds
			} finally {
				// Notify when server socket has been created
				startupBarrier.countDown();
			}

			// Server: loop until stopped
			while (!isStopped()) {
				// get a semaphore so we can ensure below that no thread is still doing stuff when we want to close the server
				if (!semaphore.tryAcquire()) {
					throw new IllegalStateException("Could not get semaphore, number of possible threads is too low.");
				}

				try {
					// Start server socket and listen for client connections
					final Socket socket;
					try {
						socket = serverSocket.accept();
					} catch (@SuppressWarnings("unused") Exception e) {
						continue; // Non-blocking socket timeout occurred: try accept() again
					}

					// Get the input and output streams
					BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));         // NOSONAR - test class works only locally anyway
					PrintWriter out = new PrintWriter(socket.getOutputStream());       // NOSONAR - test class works only locally anyway

					synchronized (this) {
						/*
						 * We synchronize over the handle method and the list update because the client call completes inside
						 * the handle method and we have to prevent the client from reading the list until we've updated it.
						 * For higher concurrency, we could just change handle to return void and update the list inside the
						 * method
						 * to limit the duration that we hold the lock.
						 */
						List<SmtpMessage> messages = handleTransaction(out, input);
						receivedMail.addAll(messages);
					}
					socket.close();
				} finally {
					semaphore.release();
				}
			}
		} catch (Exception e) {
			// TODO: Should throw an appropriate exception here
			log.log(Level.SEVERE, "Caught exception: ", e);
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					log.log(Level.SEVERE, "Caught exception: ", e);
				}
			}
		}
	}
450735
private function _open_socket($opentimeout = 0.0)
    {
        // if socket not opened, then open it (2 tries)
        if (!$this->_socket || $this->_state != 'OPENED') {
            $time = microtime(true);
            $this->_spool[0]['Times']['open'][0] = $time;

            $errno = '';
            $errstr = '';
            $this->_socket = @fsockopen($this->_host, $this->_port, $errno, $errstr, 1.8); // first try
            if (!$this->_socket) {

                if ($opentimeout >= 1.0) {
                    $this->_socket = @fsockopen($this->_host, $this->_port, $errno, $errstr, $opentimeout);
                }
                if (!$this->_socket) {
                    $this->_bad('Error('.$errno.')'.$errstr.', connection failed!');

                    return;
                }
            }
            $this->_state = 'OPENED';
            // new socket connection : reset all pending request original values
            for ($i = 0; $i < count($this->_spool); $i++) {
                $this->_spool[$i]['State'] = 'OPEN';
                $this->_spool[$i]['DatasSent'] = 0;
                $this->_spool[$i]['Response'] = '';
                $this->_spool[$i]['Headers'] = array();
            }
            $this->_response = '';
            $this->_query_num = 0;
            $this->_query_time = time();
            $time = microtime(true);
            $this->_spool[0]['Times']['open'][1] = $time - $this->_spool[0]['Times']['open'][0];
        }
    }
504863
private function openHandle()
	{
		if( !$this->host )
			throw new \Exception('Host is not defined.');

		$this->handle= ($this->scheme==='https'?
			fsockopen( 'ssl://'.$this->host, $this->port?:443 )
		:
			fsockopen( $this->host, $this->port?:80 )
		);
	}