List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
From source file:com.alibaba.wasp.zookeeper.ZKUtil.java
/** * Gets the statistics from the given server. * * @param server/*w ww . ja v a 2 s . c o m*/ * The server to get the statistics from. * @param timeout * The socket timeout to use. * @return The array of response strings. * @throws java.io.IOException * When the socket communication fails. */ public static String[] getServerStats(String server, int timeout) throws IOException { String[] sp = server.split(":"); if (sp == null || sp.length == 0) { return null; } String host = sp[0]; int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT; Socket socket = new Socket(); InetSocketAddress sockAddr = new InetSocketAddress(host, port); socket.connect(sockAddr, timeout); socket.setSoTimeout(timeout); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println("stat"); out.flush(); ArrayList<String> res = new ArrayList<String>(); while (true) { String line = in.readLine(); if (line != null) { res.add(line); } else { break; } } socket.close(); return res.toArray(new String[res.size()]); }
From source file:com.bfd.harpc.heartbeat.HeartBeatTask.java
/** * socket?/*from w w w .j a v a2 s . c o m*/ * <p> * * @param serverNode */ private boolean checkSocket(ServerNode serverNode) { boolean isValid = false; Socket socket = null; try { InetSocketAddress socketAddress = new InetSocketAddress(serverNode.getIp(), serverNode.getPort()); socket = new Socket(); socket.connect(socketAddress, heartbeatTimeout); isValid = true; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Heartbeat to remote " + serverNode.genAddress() + " success!"); } } catch (IOException e) { LOGGER.warn("Heartbeat to remote " + serverNode.genAddress() + " failure!", e); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } } return isValid; }
From source file:org.apache.ambari.server.KdcServerConnectionVerification.java
/** * Attempt to connect to KDC server over TCP. * * @param server KDC server IP or hostname * @param port KDC server port/*from ww w . ja va 2s . c o m*/ * @return true, if server is accepting connection given port; false otherwise. */ public boolean isKdcReachableViaTCP(String server, int port) { Socket socket = null; try { socket = new Socket(); socket.connect(new InetSocketAddress(server, port), config.getKdcConnectionCheckTimeout()); } catch (UnknownHostException e) { LOG.error("Unable to resolve Kerberos Server hostname"); return false; } catch (IOException e) { LOG.error("Unable to connect to Kerberos Server"); return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.debug("Error while closing socket connection to Kerberos Server. Can be ignored."); } } } return true; }
From source file:org.eclipse.mylyn.commons.net.WebUtil.java
/** * @since 3.0/* w w w .ja v a 2 s. c o m*/ */ public static void connect(final Socket socket, final InetSocketAddress address, final int timeout, IProgressMonitor monitor) throws IOException { Assert.isNotNull(socket); WebRequest<?> executor = new WebRequest<Object>() { @Override public void abort() { try { socket.close(); } catch (IOException e) { // ignore } } public Object call() throws Exception { socket.connect(address, timeout); return null; } }; executeInternal(monitor, executor); }
From source file:org.jenkinsci.remoting.protocol.IOHubTest.java
@Test public void canAcceptSocketConnections() throws Exception { final ServerSocketChannel srv = ServerSocketChannel.open(); srv.bind(new InetSocketAddress(0)); srv.configureBlocking(false);// w w w. j av a 2 s .c om final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>(); final AtomicBoolean oops = new AtomicBoolean(false); hub.hub().register(srv, new IOHubReadyListener() { final AtomicInteger count = new AtomicInteger(0); @Override public void ready(boolean accept, boolean connect, boolean read, boolean write) { if (accept) { try { SocketChannel channel = srv.accept(); channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet()) .getBytes(Charset.forName("UTF-8")))); channel.close(); } catch (IOException e) { // ignore } hub.hub().addInterestAccept(key.get()); } else { oops.set(true); } if (connect || read || write) { oops.set(true); } } }, true, false, false, false, new IOHubRegistrationCallback() { @Override public void onRegistered(SelectionKey selectionKey) { key.set(selectionKey); } @Override public void onClosedChannel(ClosedChannelException e) { } }); Socket client = new Socket(); client.connect(srv.getLocalAddress(), 100); assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1")); client = new Socket(); client.connect(srv.getLocalAddress(), 100); assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2")); assertThat("Only ever called ready with accept true", oops.get(), is(false)); }
From source file:org.elasticsearch.hadoop.rest.commonshttp.SocksSocketFactory.java
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { InetSocketAddress socksAddr = new InetSocketAddress(socksHost, socksPort); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksAddr); int timeout = params.getConnectionTimeout(); Socket socket = new Socket(proxy); socket.setSoTimeout(timeout);/*from ww w .java 2 s .c o m*/ SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; }
From source file:fm.last.moji.tracker.impl.AbstractTrackerFactory.java
public Tracker newTracker(InetSocketAddress newAddress) throws TrackerException { log.debug("new {}()", TrackerImpl.class.getSimpleName()); Tracker tracker = null;// w w w . j a v a 2 s .c om BufferedReader reader = null; Writer writer = null; Socket socket = null; try { socket = new Socket(netConfig.getProxy()); socket.setSoTimeout(netConfig.getTrackerReadTimeout()); log.debug("Connecting to: {}:", newAddress, socket.getPort()); socket.connect(newAddress, netConfig.getTrackerConnectTimeout()); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); RequestHandler requestHandler = new RequestHandler(writer, reader); tracker = new TrackerImpl(socket, requestHandler); } catch (IOException e) { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); IOUtils.closeQuietly(socket); throw new TrackerException(e); } return tracker; }
From source file:org.oscarehr.olis.OLISProtocolSocketFactory.java
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); }//from w ww . java2s . com int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = context.getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host, port, localAddress, localPort); } else { Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } }
From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java
public void run() { Socket socket; BufferedReader input;//from ww w . j a v a 2s. c o m BufferedWriter output; kuc_log.i("Connecting to server at " + server_ip); try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } catch (SocketTimeoutException e) { kuc_log.e("Connection to server timed out!"); e.printStackTrace(); return; } catch (ConnectException e) { kuc_log.e("Connection to server was refused!"); e.printStackTrace(); return; } catch (UnknownHostException e) { kuc_log.e("You entered an invalid IP address!"); e.printStackTrace(); return; } catch (IOException e) { kuc_log.e("Error connecting to server!"); e.printStackTrace(); return; } try { kuc_log.i("Requesting a key update."); output.write("302 request key update"); output.newLine(); output.flush(); kuc_log.i("Awaiting response from server."); String update = input.readLine(); switch (update) { case "303 update": kuc_log.i("Server accepted update request, sending public key."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "304 no update": kuc_log.i("Server rejected update request, closing connection."); input.close(); output.close(); break; case "305 update unavailable": kuc_log.i("Server cannot update at this time, try again later."); input.close(); output.close(); break; default: kuc_log.i("Server sent back invalid response"); input.close(); output.close(); break; } } catch (IOException e) { kuc_log.e("Error in key update request!"); e.printStackTrace(); } }
From source file:com.supernovapps.audio.jstreamsourcer.Icecast.java
public boolean start(Socket sock) { try {//from w w w . ja va 2 s .c om this.sock = sock; sock.connect(new InetSocketAddress(host, port), timeout); sock.setSendBufferSize(64 * 1024); out = sock.getOutputStream(); PrintWriter output = new PrintWriter(out); output.println("SOURCE " + path + " HTTP/1.0"); writeAuthentication(output); writeHeaders(output); output.println(""); output.flush(); InputStreamReader isr = new InputStreamReader(sock.getInputStream()); BufferedReader in = new BufferedReader(isr); String line = in.readLine(); if (line == null || !line.contains("HTTP") || !line.contains("OK")) { if (listener != null) { listener.onError("Connection / Authentification error"); } return false; } } catch (Exception e) { e.printStackTrace(); try { if (sock != null) { sock.close(); } } catch (IOException e1) { e1.printStackTrace(); } if (listener != null) { listener.onError("Connection / Authentification error"); } return false; } started = true; if (listener != null) { listener.onConnected(); } return true; }