List of usage examples for java.net Socket setKeepAlive
public void setKeepAlive(boolean on) throws SocketException
From source file:com.clavain.munin.MuninNode.java
/** * Will load the plugin list from munin-node *///from w ww . ja v a 2 s . c o m public boolean loadPlugins() { setLoadedPlugins(new CopyOnWriteArrayList<MuninPlugin>()); String l_lastProceeded = ""; try { Socket cs = new Socket(); cs.setKeepAlive(false); cs.setSoLinger(true, 0); cs.setReuseAddress(true); cs.setSoTimeout(com.clavain.muninmxcd.socketTimeout); if (!str_via.equals("unset")) { cs.connect(new InetSocketAddress(this.getStr_via(), this.getPort()), com.clavain.muninmxcd.socketTimeout); } else { cs.connect(new InetSocketAddress(this.getHostname(), this.getPort()), com.clavain.muninmxcd.socketTimeout); } if (p.getProperty("kill.sockets").equals("true")) { SocketCheck sc = new SocketCheck(cs, getUnixtime()); sc.setHostname(this.getHostname()); com.clavain.muninmxcd.v_sockets.add(sc); } PrintStream os = new PrintStream(cs.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream())); String s = in.readLine(); if (s != null) { // Set version os.println("version"); Thread.sleep(150); s = in.readLine(); String version = s.substring(s.indexOf(":") + 1, s.length()).trim(); this.str_muninVersion = version; if (authpw != null) { // if authpw is set, verify if (!authpw.trim().equals("")) { os.println("config muninmxauth"); Thread.sleep(150); String apw = in.readLine(); s = in.readLine(); if (!apw.trim().equals(this.getAuthpw())) { logger.error("Invalid muninmxauth password for host: " + this.getHostname()); cs.close(); return false; } } } // check anyway if muninmxauth plugin is present else { os.println("config muninmxauth"); Thread.sleep(100); String apw = in.readLine(); if (!apw.trim().equals("# Unknown service")) { logger.error( "no auth password given, but muninmxauth plugin present on " + this.getHostname()); cs.close(); return false; } s = in.readLine(); } // get list of available plugins if (str_via.equals("unset")) { os.println("list"); } else { os.println("list " + str_hostname); } Thread.sleep(250); s = in.readLine(); // if response is empty and host is not via, do a list $hostname if (s.trim().equals("") && str_via.equals("unset")) { logger.info("Plugin Response Empty on " + this.getHostname() + " trying to load with list $hostname"); os.println("list " + this.getHostname()); Thread.sleep(250); s = in.readLine(); } String l_tmp; StringTokenizer l_st = new StringTokenizer(s, " "); // create plugin MuninPlugin l_mp = new MuninPlugin(); // negative support ArrayList<String> tmp_negatives = new ArrayList<String>(); while (l_st.hasMoreTokens()) { String l_strPlugin = l_st.nextToken(); // check for track_pkg and muninmx essentials if (l_strPlugin.equals("muninmx_trackpkg")) { this.setTrack_pkg(true); continue; } // got essentials? if (l_strPlugin.equals("muninmx_essentials")) { this.setEssentials(true); continue; } if (isPluginIgnored(l_strPlugin.toUpperCase())) { continue; } l_mp.setPluginName(l_strPlugin); os.println("config " + l_strPlugin); // create graphs for plugin int l_iGraphsFound = 0; int l_iTmp = 0; MuninGraph l_mg = new MuninGraph(); l_mg.setQueryInterval(this.getQueryInterval()); while ((l_tmp = in.readLine()) != null) { if (l_tmp.startsWith(".")) { break; } // collect graphs only for plugin String l_strName; String l_strType; String l_strValue; if (!l_tmp.contains("graph_") && !l_tmp.trim().equals("") && !l_tmp.contains("host_name") && !l_tmp.contains("multigraph") && !l_tmp.trim().equals("graph no") && !l_tmp.trim().equals("# Bad exit") && !l_tmp.trim().contains("info Currently our peer") && !l_tmp.trim().startsWith("#") && !l_tmp.trim().contains("Bonding interface errors")) { l_lastProceeded = l_tmp; l_strName = l_tmp.substring(0, l_tmp.indexOf(".")); l_strType = l_tmp.substring(l_tmp.indexOf(".") + 1, l_tmp.indexOf(" ")); l_strValue = l_tmp.substring(l_tmp.indexOf(" ") + 1, l_tmp.length()); //System.err.println("Name: " + l_strName + " Type: " + l_strType + " Value: " + l_strValue); if (l_strType.equals("label")) { l_iTmp++; if (l_iTmp > 1) { l_mp.addGraph(l_mg); l_mg = new MuninGraph(); l_mg.setQueryInterval(this.getQueryInterval()); } l_mg.setGraphName(l_strName); l_mg.setGraphLabel(l_strValue); } else if (l_strType.equals("draw")) { l_mg.setGraphDraw(l_strValue); } else if (l_strType.equals("type")) { l_mg.setGraphType(l_strValue); } else if (l_strType.equals("info")) { l_mg.setGraphInfo(l_strValue); } else if (l_strType.equals("negative")) { // add to temporary negative list to set negatives later tmp_negatives.add(l_strValue); } //System.out.println(l_strName); //System.out.println(l_strType); //System.out.println(l_strValue); } else { // set plugin title if (l_tmp.contains("graph_title")) { l_mp.setPluginTitle(l_tmp.substring(12, l_tmp.length())); } // set plugin info, if any if (l_tmp.contains("graph_info")) { l_mp.setPluginInfo(l_tmp.substring(11, l_tmp.length())); } // set graph category if (l_tmp.contains("graph_category")) { l_mp.setPluginCategory(l_tmp.substring(15, l_tmp.length())); } // set graph vlabel if (l_tmp.contains("graph_vlabel")) { l_mp.setPluginLabel(l_tmp.substring(13, l_tmp.length())); } // set plugin title if (l_tmp.contains("graph_mxdraw")) { l_mp.setStr_LineMode(l_tmp.substring(13, l_tmp.length())); } } } // add to pluginlist l_mp.addGraph(l_mg); Iterator it = l_mp.getGraphs().iterator(); while (it.hasNext()) { MuninGraph l_mpNg = (MuninGraph) it.next(); if (tmp_negatives.contains(l_mpNg.getGraphName())) { l_mpNg.setNegative(true); } } // add plugin if it got valid graphs and add nodeid (req. for alerts) if (l_mp.getGraphs().size() > 0) { l_mp.set_NodeId(this.getNode_id()); getLoadedPlugins().add(l_mp); } // flush temporary negatives tmp_negatives.clear(); l_mp = null; l_mp = new MuninPlugin(); //String l_strGraphTitle = s.substring(s.indexOf("graph_title") + 11,s.length()); //System.out.println(" - " + l_strGraphTitle); } cs.close(); in.close(); os.close(); last_plugin_load = getUnixtime(); //System.out.println(s); } else { cs.close(); in.close(); os.close(); logger.warn("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + "). Check connectivity or munin-node"); } /* for (MuninPlugin l_mn : getLoadedPlugins()) { i_GraphCount = i_GraphCount + l_mn.getGraphs().size(); logger.debug(l_mn.getGraphs().size() + " graphs found for plugin: " + l_mn.getPluginName().toUpperCase() + " on node: " + this.getNodename()); }*/ } catch (Exception ex) { logger.error("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + ") : " + ex.getMessage()); ex.printStackTrace(); return false; } return true; }
From source file:android.core.SSLSocketTest.java
/** * Does a number of HTTPS requests on some host and consumes the response. * We don't use the HttpsUrlConnection class, but do this on our own * with the SSLSocket class. This gives us a chance to test the basic * behavior of SSL./*from w w w .j av a 2 s. c o m*/ * * @param host The host name the request is being sent to. * @param port The port the request is being sent to. * @param path The path being requested (e.g. "/index.html"). * @param outerLoop The number of times we reconnect and do the request. * @param innerLoop The number of times we do the request for each * connection (using HTTP keep-alive). * @param delay The delay after each request (in seconds). * @throws IOException When a problem occurs. */ private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path, int outerLoop, int innerLoop, int delay, int timeout) throws IOException { InetSocketAddress address = new InetSocketAddress(host, port); for (int i = 0; i < outerLoop; i++) { // Connect to the remote host Socket socket = secure ? socketFactory.createSocket() : new Socket(); if (timeout >= 0) { socket.setKeepAlive(true); socket.setSoTimeout(timeout * 1000); } socket.connect(address); // Get the streams OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); try { DataInputStream input = new DataInputStream(socket.getInputStream()); try { for (int j = 0; j < innerLoop; j++) { android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1"); // Send a request writer.println("GET https://" + host + path + " HTTP/1.1\r"); writer.println("Host: " + host + "\r"); writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r"); writer.println("\r"); writer.flush(); int length = -1; boolean chunked = false; String line = input.readLine(); if (line == null) { throw new IOException("No response from server"); // android.util.Log.d("SSLSocketTest", "No response from server"); } // Consume the headers, check content length and encoding type while (line != null && line.length() != 0) { // System.out.println(line); int dot = line.indexOf(':'); if (dot != -1) { String key = line.substring(0, dot).trim(); String value = line.substring(dot + 1).trim(); if ("Content-Length".equalsIgnoreCase(key)) { length = Integer.valueOf(value); } else if ("Transfer-Encoding".equalsIgnoreCase(key)) { chunked = "Chunked".equalsIgnoreCase(value); } } line = input.readLine(); } assertTrue("Need either content length or chunked encoding", length != -1 || chunked); // Consume the content itself if (chunked) { length = Integer.parseInt(input.readLine(), 16); while (length != 0) { byte[] buffer = new byte[length]; input.readFully(buffer); input.readLine(); length = Integer.parseInt(input.readLine(), 16); } input.readLine(); } else { byte[] buffer = new byte[length]; input.readFully(buffer); } // Sleep for the given number of seconds try { Thread.sleep(delay * 1000); } catch (InterruptedException ex) { // Shut up! } } } finally { input.close(); } } finally { writer.close(); } // Close the connection socket.close(); } }
From source file:org.jboss.remoting.transport.http.HTTPServerInvoker.java
public void run() { try {/*from w ww . j a v a 2 s . c o m*/ if (newServerSocketFactory) { log.debug("got notice about new ServerSocketFactory"); try { log.debug("refreshing server socket"); refreshServerSocket(); } catch (IOException e) { log.debug("could not refresh server socket"); log.debug("message is: " + e.getMessage()); } log.debug("server socket refreshed"); } Socket socket = serverSocket.accept(); BufferedInputStream dataInput = null; BufferedOutputStream dataOutput = null; if (socket != null) { // tell the pool to start another thread to listen for more socket requests. httpThreadPool.run(this); try { boolean keepAlive = true; // start processing incoming request from client. will try to keep current connection alive socket.setKeepAlive(true); socket.setSoTimeout(keepAliveTimeout); DataInputStream realdataInput = new DataInputStream(socket.getInputStream()); DataOutputStream realdataOutput = new DataOutputStream(socket.getOutputStream()); while (keepAlive) { dataOutput = new BufferedOutputStream(realdataOutput, 512); dataInput = new BufferedInputStream(realdataInput, 512); keepAlive = processRequest(dataInput, dataOutput); } } catch (Throwable thr) { if (running) { log.error("Error processing incoming request.", thr); } } finally { if (dataInput != null) { try { dataInput.close(); } catch (Exception e) { log.warn("Error closing resource.", e); } } if (dataOutput != null) { try { dataOutput.close(); } catch (Exception e) { log.warn("Error closing resource.", e); } } try { socket.close(); } catch (Exception e) { log.warn("Error closing resource.", e); } } } } catch (Throwable thr) { if (running) { log.error("Error processing incoming request.", thr); } } }
From source file:hudson.cli.CLI.java
/** * @deprecated Specific to {@link Mode#REMOTING}. */// ww w . j a v a2s . c om @Deprecated private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException { LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint); if (authorization != null) { LOGGER.warning("-auth ignored when using JNLP agent port"); } final Socket s = new Socket(); // this prevents a connection from silently terminated by the router in between or the other peer // and that goes without unnoticed. However, the time out is often very long (for example 2 hours // by default in Linux) that this alone is enough to prevent that. s.setKeepAlive(true); // we take care of buffering on our own s.setTcpNoDelay(true); OutputStream out; if (httpsProxyTunnel != null) { String[] tokens = httpsProxyTunnel.split(":"); LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port", new Object[] { tokens[0], tokens[1] }); s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1]))); PrintStream o = new PrintStream(s.getOutputStream()); o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n"); // read the response from the proxy ByteArrayOutputStream rsp = new ByteArrayOutputStream(); while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) { int ch = s.getInputStream().read(); if (ch < 0) throw new IOException("Failed to read the HTTP proxy response: " + rsp); rsp.write(ch); } String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine(); if (head == null) { throw new IOException("Unexpected empty response"); } if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) { s.close(); LOGGER.log(Level.SEVERE, "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP."); throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp); } // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well. // So instead of relying on it, we'll just send the close command and then let the server // cut their side, then close the socket after the join. out = new SocketOutputStream(s) { @Override public void close() throws IOException { // ignore } }; } else { s.connect(clip.endpoint, 3000); out = SocketChannelStream.out(s); } closables.add(new Closeable() { public void close() throws IOException { s.close(); } }); Connection c = new Connection(SocketChannelStream.in(s), out); switch (clip.version) { case 1: DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI-connect"); // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor. break; case 2: DataInputStream dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI2-connect"); String greeting = dis.readUTF(); if (!greeting.equals("Welcome")) throw new IOException("Handshaking failed: " + greeting); try { byte[] secret = c.diffieHellman(false).generateSecret(); SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES"); c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding"); // validate the instance identity, so that we can be sure that we are talking to the same server // and there's no one in the middle. byte[] signature = c.readByteArray(); if (clip.identity != null) { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(clip.getIdentity()); verifier.update(secret); if (!verifier.verify(signature)) throw new IOException("Server identity signature validation failed."); } } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to negotiate transport security").initCause(e); } } return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in), new BufferedOutputStream(c.out)); }
From source file:edu.vt.middleware.gator.log4j.SocketServer.java
/** {@inheritDoc}. */ public void run() { while (serverSocket != null && serverSocket.isBound()) { logger.info("Waiting to accept a new client."); Socket socket = null; InetAddress inetAddress = null; try {// w w w .j av a2s .co m socket = serverSocket.accept(); inetAddress = socket.getInetAddress(); // Validate newly-connected client if (eventHandlerMap.keySet().size() >= maxClients) { throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded."); } final ProjectConfig project = getProject(inetAddress); if (project == null) { throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects."); } // Explicitly enable TCP keep alives to try to help reclaim resources // from dead clients socket.setKeepAlive(true); logger.info("Accepted connection from client " + inetAddress); logger.info("Configuring logger repository for " + inetAddress); final LoggerRepository repo = getLoggerRepository(project); configurator.configure(project, repo); logger.info("Logger repository configured successfully."); final LoggingEventHandler handler = new LoggingEventHandler(socket, repo, eventExecutor); handler.getSocketCloseListeners().add(this); eventHandlerMap.put(inetAddress, handler); handlerExecutor.execute(handler); } catch (UnauthorizedClientException e) { logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(), e.getClient())); if (socket != null && !socket.isClosed()) { logger.info("Closing socket for rejected host."); try { socket.close(); } catch (IOException ioex) { logger.error("Error closing client socket.", ioex); } } } catch (SocketException e) { // Check whether this is caused by a stop() invocation: // calling stop() closes server socket, which throws SocketException // from blocking accept() call if (serverSocket == null) { logger.info("Ignoring SocketException caused by stop() invocation."); } else { logger.error(e); } } catch (Exception e) { logger.error(e); } } }
From source file:edu.vt.middleware.gator.server.SocketServer.java
/** {@inheritDoc}. */ public void run() { while (serverSocket != null && serverSocket.isBound()) { logger.info("Waiting to accept a new client."); Socket socket = null; InetAddress inetAddress = null; try {//from w w w. j ava 2s .c o m socket = serverSocket.accept(); inetAddress = socket.getInetAddress(); // Validate newly-connected client if (eventHandlerMap.keySet().size() >= maxClients) { throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded."); } final ProjectConfig project = getProject(inetAddress); if (project == null) { throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects."); } // Explicitly enable TCP keep alives to try to help reclaim resources // from dead clients socket.setKeepAlive(true); logger.info("Accepted connection from client " + inetAddress); logger.info("Configuring logger repository for " + inetAddress); final LoggingEngine engine = getLoggingEngine(project); if (engine != null) { engine.register(inetAddress, project); logger.info("Successfully configured " + engine); final LoggingEventHandler handler = new LoggingEventHandler(socket, engine, eventExecutor); handler.getSocketCloseListeners().add(this); eventHandlerMap.put(inetAddress, handler); handlerExecutor.execute(handler); } else { logger.warn(String.format("Logging engine not found for %s. Closing socket for %s.", project, inetAddress)); socket.close(); } } catch (UnauthorizedClientException e) { logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(), e.getClient())); if (socket != null && !socket.isClosed()) { logger.info("Closing socket for rejected host."); try { socket.close(); } catch (IOException ioex) { logger.error("Error closing client socket.", ioex); } } } catch (SocketException e) { // Check whether this is caused by a stop() invocation: // calling stop() closes server socket, which throws SocketException // from blocking accept() call if (serverSocket == null) { logger.info("Ignoring SocketException caused by stop() invocation."); } else { logger.error(e); } } catch (Exception e) { logger.error(e); } } }
From source file:net.jotel.ws.client.WebSocketClient.java
private Socket createSocket() throws IOException { Socket s; if (secure) { SocketFactory factory = SSLSocketFactory.getDefault(); s = factory.createSocket(host, port); } else {/*from www . j a va 2s .co m*/ s = new Socket(host, port); } s.setKeepAlive(true); s.setSoTimeout(100000); return s; }
From source file:com.mirth.connect.connectors.tcp.TcpReceiver.java
private void initSocket(Socket socket) throws SocketException { logger.debug("Initializing socket (" + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ")."); socket.setReceiveBufferSize(bufferSize); socket.setSendBufferSize(bufferSize); socket.setSoTimeout(timeout);//from w w w .j a v a 2 s .co m socket.setKeepAlive(connectorProperties.isKeepConnectionOpen()); socket.setReuseAddress(true); socket.setTcpNoDelay(true); }
From source file:org.mule.transport.tcp.TcpConnector.java
public void configureSocket(boolean client, Socket socket) throws SocketException { // There is some overhead in setting socket timeout and buffer size, so we're // careful here only to set if needed if (newValue(getReceiveBufferSize(), socket.getReceiveBufferSize())) { socket.setReceiveBufferSize(getReceiveBufferSize()); }/* ww w . java 2 s . c o m*/ if (newValue(getSendBufferSize(), socket.getSendBufferSize())) { socket.setSendBufferSize(getSendBufferSize()); } if (client) { if (newValue(getClientSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getClientSoTimeout()); } } else { if (newValue(getServerSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getServerSoTimeout()); } } if (newValue(getSocketSoLinger(), socket.getSoLinger())) { socket.setSoLinger(true, getSocketSoLinger()); } try { socket.setTcpNoDelay(isSendTcpNoDelay()); } catch (SocketException e) { // MULE-2800 - Bug in Solaris } socket.setKeepAlive(isKeepAlive()); }
From source file:org.unitime.timetable.solver.remote.SolverRegisterService.java
public void run() { iStartTime = new Date(); try {//from ww w . jav a 2 s . co m ConnectionFactory.init(ApplicationProperties.getProperties(), ApplicationProperties.getDataFolder()); try { while (true) { try { iServerSocket = ConnectionFactory.getServerSocketFactory().createServerSocket(Integer .parseInt(ApplicationProperties.getProperty("tmtbl.solver.register.port", "9998"))); sLog.info("Service is running at " + iServerSocket.getInetAddress().getHostName() + ":" + iServerSocket.getLocalPort()); break; } catch (BindException e) { try { sLog.warn("Prior instance of service still running"); Socket socket = ConnectionFactory.getSocketFactory().createSocket("localhost", Integer.parseInt(ApplicationProperties.getProperty("tmtbl.solver.register.port", "9998"))); RemoteIo.writeObject(socket, "quit"); Object answer = RemoteIo.readObject(socket); sLog.warn("quit command sent, answer: " + answer); socket.close(); } catch (Exception f) { sLog.warn("Unable to connect to prior instance", f); } sleep(1000); } } } catch (IOException io) { sLog.error("Unable to start service, reason: " + io.getMessage(), io); return; } while (!iServerSocket.isClosed()) { try { Socket socket = iServerSocket.accept(); socket.setKeepAlive(true); sLog.debug("Client " + socket.getInetAddress() + " connected."); (new Thread(new SolverConnection(socket))).start(); } catch (Exception e) { if (!iServerSocket.isClosed()) sLog.warn("Unable to accept new connection, reason:" + e.getMessage(), e); } } } catch (Exception e) { sLog.error("Unexpected exception occured, reason: " + e.getMessage(), e); } finally { try { if (iServerSocket != null && !iServerSocket.isClosed()) iServerSocket.close(); } catch (Exception e) { sLog.warn("Unable to close socket, reason: " + e.getMessage(), e); } } }