List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:Proxy.java
static void close(Socket in, Socket out) { if (in != null) { try {//from w ww .j av a 2s . c om in.close(); } catch (Exception ex) { } } if (out != null) { try { out.close(); } catch (Exception ex) { } } }
From source file:org.generationcp.ibpworkbench.launcher.Launcher.java
protected static boolean isTomcatRunning() { Socket socket = null; try {//from ww w. j av a 2 s .c o m socket = new Socket(TOMCAT_HOST, TOMCAT_PORT); return true; } catch (Exception e) { return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } }
From source file:com.comcast.viper.flume2storm.zookeeper.ZkTestUtils.java
/** * Utility function to send a command to the internal server. ZK servers * accepts 4 byte command strings to test their liveness. *///from ww w .j a v a 2 s .co m protected static String send4LetterWord(final String host, final int port, final String cmd) { Preconditions.checkArgument(cmd.length() == 4); try { final Socket sock = new Socket(host, port); OutputStream outstream = null; BufferedReader reader = null; try { outstream = sock.getOutputStream(); outstream.write(cmd.getBytes()); outstream.flush(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); final StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } finally { if (outstream != null) { outstream.close(); } sock.close(); if (reader != null) { reader.close(); } } } catch (final Exception e) { System.out.println(e.getMessage()); return StringUtils.EMPTY; } }
From source file:com.zhch.example.commons.http.v4_5.ProxyTunnelDemo.java
/** * demo /*from w w w. j av a 2s.c om*/ * * @throws Exception */ public final static void zhchModifyDemo() throws Exception { ProxyClient proxyClient = new ProxyClient(); HttpHost target = new HttpHost("pan.baidu.com", 80); // HttpHost proxy = new HttpHost("120.24.0.162", 80); HttpHost proxy = new HttpHost("127.0.0.1", 80); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("abc", "def"); System.out.println("before tunnel."); Socket socket = proxyClient.tunnel(proxy, target, credentials); System.out.println("after tunnel."); try { Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET); out.write("GET / HTTP/1.1\r\n"); out.write("Host: " + target.toHostString() + "\r\n"); out.write("Agent: whatever\r\n"); out.write("Connection: close\r\n"); out.write("\r\n"); out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET)); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } finally { socket.close(); } }
From source file:com.impetus.client.cassandra.common.CassandraUtilities.java
/** * * @param host//from ww w . j av a2s .c o m * @param port * @return */ public static boolean verifyConnection(String host, int port) { Socket socket = null; try { socket = new Socket(host, port); socket.setReuseAddress(true); socket.setSoLinger(true, 0); boolean isConnected = socket.isConnected(); return isConnected; } catch (UnknownHostException e) { logger.warn("{}:{} is still down", host, port); return false; } catch (IOException e) { logger.warn("{}:{} is still down", host, port); return false; } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { logger.warn("{}:{} is still down", host, port); } } }
From source file:com.liveramp.hank.test.ZkTestCase.java
private static boolean waitForServerUp(int port, long timeout) { long start = System.currentTimeMillis(); while (true) { try {//from w w w .j av a 2s. c o m Socket sock = new Socket("localhost", port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); Reader isr = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isr); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server localhost:" + port + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; }
From source file:SimpleProxyServer.java
/** * runs a single-threaded proxy server on * the specified local port. It never returns. *//*w w w . j a v a2s. c o m*/ public static void runServer(String host, int remoteport, int localport) throws IOException { // Create a ServerSocket to listen for connections with ServerSocket ss = new ServerSocket(localport); final byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (true) { Socket client = null, server = null; try { // Wait for a connection on the local port client = ss.accept(); final InputStream streamFromClient = client.getInputStream(); final OutputStream streamToClient = client.getOutputStream(); // Make a connection to the real server. // If we cannot connect to the server, send an error to the // client, disconnect, and continue waiting for connections. try { server = new Socket(host, remoteport); } catch (IOException e) { PrintWriter out = new PrintWriter(streamToClient); out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n"); out.flush(); client.close(); continue; } // Get server streams. final InputStream streamFromServer = server.getInputStream(); final OutputStream streamToServer = server.getOutputStream(); // a thread to read the client's requests and pass them // to the server. A separate thread for asynchronous. Thread t = new Thread() { public void run() { int bytesRead; try { while ((bytesRead = streamFromClient.read(request)) != -1) { streamToServer.write(request, 0, bytesRead); streamToServer.flush(); } } catch (IOException e) { } // the client closed the connection to us, so close our // connection to the server. try { streamToServer.close(); } catch (IOException e) { } } }; // Start the client-to-server request thread running t.start(); // Read the server's responses // and pass them back to the client. int bytesRead; try { while ((bytesRead = streamFromServer.read(reply)) != -1) { streamToClient.write(reply, 0, bytesRead); streamToClient.flush(); } } catch (IOException e) { } // The server closed its connection to us, so we close our // connection to our client. streamToClient.close(); } catch (IOException e) { System.err.println(e); } finally { try { if (server != null) server.close(); if (client != null) client.close(); } catch (IOException e) { } } } }
From source file:com.yahoo.pulsar.zookeeper.LocalBookkeeperEnsemble.java
public static boolean waitForServerUp(String hp, long timeout) { long start = MathUtils.now(); String split[] = hp.split(":"); String host = split[0];//from w w w . j a va 2 s. com int port = Integer.parseInt(split[1]); while (true) { try { Socket sock = new Socket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { LOG.info("Server UP"); return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server " + hp + " not up " + e); } if (MathUtils.now() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; }
From source file:info.bonjean.quinkana.Main.java
private static void run(String[] args) throws QuinkanaException { Properties properties = new Properties(); InputStream inputstream = Main.class.getResourceAsStream("/config.properties"); try {/*ww w.j av a 2s . c om*/ properties.load(inputstream); inputstream.close(); } catch (IOException e) { throw new QuinkanaException("cannot load internal properties", e); } String name = (String) properties.get("name"); String description = (String) properties.get("description"); String url = (String) properties.get("url"); String version = (String) properties.get("version"); String usage = (String) properties.get("help.usage"); String defaultHost = (String) properties.get("default.host"); int defaultPort = Integer.valueOf(properties.getProperty("default.port")); ArgumentParser parser = ArgumentParsers.newArgumentParser(name).description(description) .epilog("For more information, go to " + url).version("${prog} " + version).usage(usage); parser.addArgument("ACTION").type(Action.class).choices(Action.tail, Action.list).dest("action"); parser.addArgument("-H", "--host").setDefault(defaultHost) .help(String.format("logstash host (default: %s)", defaultHost)); parser.addArgument("-P", "--port").type(Integer.class).setDefault(defaultPort) .help(String.format("logstash TCP port (default: %d)", defaultPort)); parser.addArgument("-f", "--fields").nargs("+").help("fields to display"); parser.addArgument("-i", "--include").nargs("+").help("include filter (OR), example host=example.com") .metavar("FILTER").type(Filter.class); parser.addArgument("-x", "--exclude").nargs("+") .help("exclude filter (OR, applied after include), example: severity=debug").metavar("FILTER") .type(Filter.class); parser.addArgument("-s", "--single").action(Arguments.storeTrue()).help("display single result and exit"); parser.addArgument("--version").action(Arguments.version()).help("output version information and exit"); Namespace ns = parser.parseArgsOrFail(args); Action action = ns.get("action"); List<String> fields = ns.getList("fields"); List<Filter> includes = ns.getList("include"); List<Filter> excludes = ns.getList("exclude"); boolean single = ns.getBoolean("single"); String host = ns.getString("host"); int port = ns.getInt("port"); final Socket clientSocket; final InputStream is; try { clientSocket = new Socket(host, port); is = clientSocket.getInputStream(); } catch (IOException e) { throw new QuinkanaException("cannot connect to the server " + host + ":" + port, e); } // add a hook to ensure we clean the resources when leaving Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }); // prepare JSON parser ObjectMapper mapper = new ObjectMapper(); JsonFactory jsonFactory = mapper.getFactory(); JsonParser jp; try { jp = jsonFactory.createParser(is); } catch (IOException e) { throw new QuinkanaException("error during JSON parser creation", e); } JsonToken token; // action=list if (action.equals(Action.list)) { try { // do this in a separate loop to not pollute the main loop while ((token = jp.nextToken()) != null) { if (token != JsonToken.START_OBJECT) continue; // parse object JsonNode node = jp.readValueAsTree(); // print fields Iterator<String> fieldNames = node.fieldNames(); while (fieldNames.hasNext()) System.out.println(fieldNames.next()); System.exit(0); } } catch (IOException e) { throw new QuinkanaException("error during JSON parsing", e); } } // action=tail try { while ((token = jp.nextToken()) != null) { if (token != JsonToken.START_OBJECT) continue; // parse object JsonNode node = jp.readValueAsTree(); // filtering (includes) if (includes != null) { boolean skip = true; for (Filter include : includes) { if (include.match(node)) { skip = false; break; } } if (skip) continue; } // filtering (excludes) if (excludes != null) { boolean skip = false; for (Filter exclude : excludes) { if (exclude.match(node)) { skip = true; break; } } if (skip) continue; } // if no field specified, print raw output (JSON) if (fields == null) { System.out.println(node.toString()); if (single) break; continue; } // formatted output, build and print the string StringBuilder sb = new StringBuilder(128); for (String field : fields) { if (sb.length() > 0) sb.append(" "); if (node.get(field) != null && node.get(field).textValue() != null) sb.append(node.get(field).textValue()); } System.out.println(sb.toString()); if (single) break; } } catch (IOException e) { throw new QuinkanaException("error during JSON parsing", e); } }
From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java
static String checkListeningPort(String host, int port) { Socket s = null; try {//w w w .j a va2 s . co m s = new Socket(host, port); return host + ":" + port + "is listening;\n"; } catch (Exception e) { return "checking listening port for " + host + ":" + port + " result false for reason " + e.getMessage(); } finally { if (s != null) try { s.close(); } catch (Exception e) { } } }