List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java
/** * common.agent.discovery.pingport ????????IP?? * ?TCP???????true?//from w w w .j a v a 2 s . co m * ?????????false? * * @param facilityId * @return * @throws UnknownHostException * @throws IOException */ public static boolean sendManagerDiscoveryInfo(String facilityId) throws UnknownHostException, IOException { String managerIpAddr = ""; boolean successFlag = true; String agentIpAddr = ""; int pingPort; // ??????????????????? pingPort = HinemosPropertyUtil.getHinemosPropertyNum("common.agent.discovery.pingport", Long.valueOf(24005)) .intValue(); if (pingPort < 1 || pingPort > 65535) { return false; } // ???????IP? try { // DNS????(agent.connection.dnsname??) Hinemos ver 4.0.2? managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.dnsname", ""); // IP??(agent.connection.dnsname?) if (managerIpAddr == null || "".equals(managerIpAddr)) { managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.ipaddres", InetAddress.getLocalHost().getHostAddress()); } } catch (UnknownHostException e) { throw e; } // FIXME ?????????????????????????????? Socket socket = null; InputStream is = null; try { String sendDataStr = "managerIp=" + managerIpAddr + ",agentFacilityId=" + facilityId; byte[] data = sendDataStr.getBytes(); byte[] msg = new byte[data.length]; agentIpAddr = NodeProperty.getProperty(facilityId).getAvailableIpAddress(); m_log.info("trying to establish connection to hinemos agent server at " + agentIpAddr + ":" + pingPort); socket = new Socket(agentIpAddr, pingPort); m_log.info("established the connection to the hinemos agent server at " + agentIpAddr); is = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(data); m_log.info("sent the message " + new String(data)); // ??? int totalBytesRcvd = 0; int bytesRcvd; while (totalBytesRcvd < data.length) { if ((bytesRcvd = is.read(msg, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) { continue; } totalBytesRcvd += bytesRcvd; } m_log.info("received the message: " + new String(msg)); } catch (Exception e) { successFlag = false; m_log.warn("facilityId: " + facilityId + ", " + e.getMessage()); } finally { try { if (is != null) { is.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { throw e; } } return successFlag; }
From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java
public void close(MsgContext ep) throws IOException { Socket s = (Socket) ep.getNote(socketNote); SelectionKey key = s.getChannel().keyFor(selector); if (key != null) { key.cancel();/* w w w . j a v a2s . c o m*/ } s.close(); }
From source file:com.jayway.maven.plugins.android.AbstractEmulatorMojo.java
/** * Sends a user command to the running emulator via its telnet interface. * * @param port The emulator's telnet port. * @param command The command to execute on the emulator's telnet interface. * @return Whether sending the command succeeded. *//*from ww w .j a v a 2 s . c om*/ private boolean sendEmulatorCommand( //final Launcher launcher, //final PrintStream logger, final int port, final String command) { Callable<Boolean> task = new Callable<Boolean>() { public Boolean call() throws IOException { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { return false; } out.write(command); out.write("\r\n"); } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // Do nothing } } return true; } private static final long serialVersionUID = 1L; }; boolean result = false; try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(task); result = future.get(); } catch (Exception e) { getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e)); } return result; }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops the ARO Data Collector trace by stopping the tcpdump process. * //from w w w .java2 s . com * @throws java.io.IOException * @throws java.net.UnknownHostException */ public void requestDataCollectorStop() { dataCollectorStopWatchTimer(); try { if (DEBUG) { Log.i(TAG, "enter requestDataCollectorStop at " + System.currentTimeMillis()); } logTcpdumpPid(); final Socket tcpdumpsocket = new Socket(InetAddress.getByName("localhost"), 50999); final OutputStream out = tcpdumpsocket.getOutputStream(); out.write("STOP".getBytes("ASCII")); out.flush(); out.close(); tcpdumpsocket.close(); getBatteryInfo(); getAlarmInfo(outAlarmInfoEndFileName); restoreDebugMaskDefault(); if (DEBUG) { Log.i(TAG, "exit requestDataCollectorStop at " + System.currentTimeMillis()); } } catch (Exception e) { Log.e(TAG, "exception in stopTcpDump", e); //for debugging, check if tcpdump is still running logTcpdumpPid(); } }
From source file:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM2.java
@Override public void run() { try {//from w w w .ja v a 2 s .co m while (true) { Socket socket = server.accept(); log.info("Cliente conectado " + socket.getInetAddress()); try { PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); printWriter.println(new Date().toString() + "Teste Servidor"); log.info("Sinal de autenticao enviado para o Cliente " + new Date().toString()); //Faz verificao no fluxo de entrada do Objeto ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); try { //faz a leitura do Objeto de entrada Object readObject = objectInputStream.readObject(); if (readObject instanceof SendSMSMessage) { try { SendSMSMessage smsMessage = (SendSMSMessage) readObject; // Thread.sleep(random.nextInt(10000)); ponte.set(smsMessage); new Thread(new ConsumerSendSMSMessage(ponte), "PONTE_ASYNC_DSSOCKETSIM2").start(); listaSMS.add(smsMessage); objectInputStream.close(); socket.close(); if (listaSMS.size() > 0 && !listaSMS.isEmpty()) { DServiceModem2 md2 = new DServiceModem2(listaSMS, 10000); new Thread(md2, "MODEM 2").start(); listaSMS.clear(); } } catch (InterruptedException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } } catch (ClassNotFoundException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } finally { try { socket.close(); } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } } } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } finally { try { server.close(); } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.hqme.cm.cache.StreamingServer.java
private void handleRequests() { // android.os.Debug.waitForDebugger(); try {// w ww. ja v a 2s. c om Socket client = null; while (!isStopping) try { client = null; client = serverSocket.accept(); // prevent connections from remote internet addresses; clients must playback from localhost sockets only SocketAddress socketAddress = client.getRemoteSocketAddress(); if (InetSocketAddress.class.isInstance(socketAddress)) { String hostName = ((InetSocketAddress) socketAddress).getHostName(); if (!"localhost".equalsIgnoreCase(hostName)) { // UntenCacheService.debugLog(sTag, "handleRequests: client.getRemoteSocketAddress().getHostName(): %s", hostName); client.close(); client = null; continue; } } } catch (IOException fault) { isStopping = true; } finally { synchronized (clientBox) { if (isStopping) { for (int i = 0; i < clientBox.length; i++) { if (clientBox[i] != null && clientBox[i].thread != null && clientBox[i].thread.isAlive()) { UntenCacheService.debugLog(sTag, "run: Stopping client # %d", i); clientBox[i].handler.isStopRequested = true; } } } else if (client != null) { int i = 0; for (i = 0; i < clientBox.length; i++) { if (clientBox[i] == null || !clientBox[i].thread.isAlive()) { clientBox[i] = new ClientBox(); clientBox[i].handler = new ClientHandler(client, i); clientBox[i].thread = new Thread(clientBox[i].handler); clientBox[i].thread.setDaemon(true); clientBox[i].thread.start(); // UntenCacheService.debugLog(sTag, "handleRequests", "Accepted client # %d", i); break; } } if (i == clientBox.length) { // End with no slot for it. client.close(); } } } } } catch (Exception fault) { fault.printStackTrace(); } finally { if (serverSocket != null) { try { serverSocket.close(); serverSocket = null; } catch (Throwable ignore) { } } clientBox = null; } }
From source file:com.jcraft.weirdx.WeirdX.java
public void weirdx_start(Container container) throws ConnectException { if (xdmcpmode != null) { LOG.debug("XDMC Mode = " + xdmcpmode); if (xdmcpmode.equals("query")) { xdmcp = new XDMCP(xdmcpaddr, myAddress, displayNumber); } else if (xdmcpmode.equals("broadcast")) { xdmcp = new XDMCP(XDMCP.BroadcastQuery, xdmcpaddr, myAddress, displayNumber); } else if (xdmcpmode.equals("indirect")) { xdmcp = new XDMCP(XDMCP.IndirectQuery, xdmcpaddr, myAddress, displayNumber); }//from w w w. j a v a 2 s .co m } if (sxrexec != null && sxrexec.equals("yes")) { xrexec = new XRexec(myAddress, displayNumber); } weirdx_init(container); InputStream in; OutputStream out; InputOutput client = null; if (xdmcp != null) { Client.addListener((ClientListener) xdmcp); xdmcp.start(); } if (jdxpc != null) { (new SpawnJDxpc(this)).start(); } if (ssshrexec != null) { if (ssshrexec.equals("yes")) { (new SpawnSSHRexec(this)).start(); } } byte[] byte_order = new byte[1]; try { Socket socket = null; while (true && weirdx != null) { try { socket = displaysocket.accept(); } catch (Exception e) { LOG.error(e); if (e instanceof NullPointerException) { weirdx = null; break; } continue; } if (!Acl.check(socket.getInetAddress())) { LOG.error("ACL warning: unauthorized access from " + socket.getInetAddress()); try { socket.close(); } catch (Exception e) { } ; continue; } try { socket.setTcpNoDelay(true); } catch (Exception eeee) { //System.out.println(eeee+" tcpnodelay"); } client = null; in = socket.getInputStream(); out = socket.getOutputStream(); try { in.read(byte_order, 0, 1); } catch (Exception e) { continue; } // 0x6c LSB // 0x42 MSB if (byte_order[0] == 0x6c) { client = new IOLSB(); } else if (byte_order[0] == 0x42) { client = new IOMSB(); } else { LOG.warn("protocol: error " + Integer.toHexString(byte_order[0])); continue; } client.setInputStream(in); client.setOutputStream(out); Client foo = new Client(client); if (foo.index != -1) { foo.start(); } else { // System.err.println("running over clients table"); } } } catch (IOException e) { LOG.error("IO Error: " + e.getLocalizedMessage()); } // stop(); // ?? }
From source file:monasca.api.integration.docker.ITInfluxDBTest.java
private void waitForPortReady(String host, int port) { System.out.println("waiting to connect to host [" + host + "] on port [" + port + "]"); Socket s = null; boolean isPortReady = false; int tryCount = 0; while (!isPortReady) { if (tryCount >= MAX_CONNECT_PORT_TRIES) { System.err.println("Failed to connect to host [" + host + "] on port [" + port + "] in " + "[" + tryCount + "] tries"); tearDown();//from ww w . j a va 2 s.c o m System.exit(-1); } try { s = new Socket(); s.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(host, port); s.connect(sa, 50000); isPortReady = true; System.out.println( "Took " + tryCount + " tries to connect to host [" + host + "] on port" + "[" + port + "]"); } catch (Exception e) { tryCount++; } } if (s != null) { try { s.close(); } catch (Exception e) { System.err.print(e); } } }
From source file:edu.cmu.ark.AnalysisUtilities.java
public ParseResult parseSentence(String sentence) { String result = ""; //System.err.println(sentence); //see if a parser socket server is available int port = new Integer(GlobalProperties.getProperties().getProperty("parserServerPort", "5556")); String host = "127.0.0.1"; Socket client; PrintWriter pw;/*w w w. jav a 2 s.c om*/ BufferedReader br; String line; Tree parse = null; double parseScore = Double.MIN_VALUE; try { client = new Socket(host, port); pw = new PrintWriter(client.getOutputStream()); br = new BufferedReader(new InputStreamReader(client.getInputStream())); pw.println(sentence); pw.flush(); //flush to complete the transmission while ((line = br.readLine()) != null) { //if(!line.matches(".*\\S.*")){ // System.out.println(); //} if (br.ready()) { line = line.replaceAll("\n", ""); line = line.replaceAll("\\s+", " "); result += line + " "; } else { parseScore = new Double(line); } } br.close(); pw.close(); client.close(); if (parse == null) { parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; } if (GlobalProperties.getDebug()) System.err.println("result (parse):" + result); parse = readTreeFromString(result); return new ParseResult(true, parse, parseScore); } catch (Exception ex) { if (GlobalProperties.getDebug()) System.err.println("Could not connect to parser server."); //ex.printStackTrace(); } System.err.println("parsing:" + sentence); //if socket server not available, then use a local parser object if (parser == null) { try { Options op = new Options(); String serializedInputFileOrUrl = GlobalProperties.getProperties().getProperty("parserGrammarFile", "config" + File.separator + "englishFactored.ser.gz"); parser = new LexicalizedParser(serializedInputFileOrUrl, op); int maxLength = new Integer(GlobalProperties.getProperties().getProperty("parserMaxLength", "40")) .intValue(); parser.setMaxLength(maxLength); parser.setOptionFlags("-outputFormat", "oneline"); } catch (Exception e) { e.printStackTrace(); } } try { if (parser.parse(sentence)) { parse = parser.getBestParse(); //remove all the parent annotations (this is a hacky way to do it) String ps = parse.toString().replaceAll("\\[[^\\]]+/[^\\]]+\\]", ""); parse = AnalysisUtilities.getInstance().readTreeFromString(ps); parseScore = parser.getPCFGScore(); return new ParseResult(true, parse, parseScore); } } catch (Exception e) { } parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; return new ParseResult(false, parse, parseScore); }
From source file:MedArkRef.AnalysisUtilities.java
public arkref.parsestuff.AnalysisUtilities.ParseResult parseSentence(String sentence) { String result = ""; //System.err.println(sentence); //see if a parser socket server is available int port = new Integer(GlobalProperties.getProperties().getProperty("parserServerPort", "5556")); String host = "127.0.0.1"; Socket client; PrintWriter pw;/*from w w w . j av a 2 s .c o m*/ BufferedReader br; String line; Tree parse = null; double parseScore = Double.MIN_VALUE; try { client = new Socket(host, port); pw = new PrintWriter(client.getOutputStream()); br = new BufferedReader(new InputStreamReader(client.getInputStream())); pw.println(sentence); pw.flush(); //flush to complete the transmission while ((line = br.readLine()) != null) { //if(!line.matches(".*\\S.*")){ // System.out.println(); //} if (br.ready()) { line = line.replaceAll("\n", ""); line = line.replaceAll("\\s+", " "); result += line + " "; } else { parseScore = new Double(line); } } br.close(); pw.close(); client.close(); if (parse == null) { parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; } if (GlobalProperties.getDebug()) System.err.println("result (parse):" + result); parse = readTreeFromString(result); return new arkref.parsestuff.AnalysisUtilities.ParseResult(true, parse, parseScore); } catch (Exception ex) { if (GlobalProperties.getDebug()) System.err.println("Could not connect to parser server."); //ex.printStackTrace(); } System.err.println("parsing:" + sentence); //if socket server not available, then use a local parser object if (parser == null) { try { Options op = new Options(); String serializedInputFileOrUrl = GlobalProperties.getProperties().getProperty("parserGrammarFile", "config" + File.separator + "englishFactored.ser.gz"); parser = new LexicalizedParser(serializedInputFileOrUrl, op); int maxLength = new Integer(GlobalProperties.getProperties().getProperty("parserMaxLength", "40")) .intValue(); parser.setMaxLength(maxLength); parser.setOptionFlags("-outputFormat", "oneline"); } catch (Exception e) { e.printStackTrace(); } } try { if (parser.parse(sentence)) { parse = parser.getBestParse(); //remove all the parent annotations (this is a hacky way to do it) String ps = parse.toString().replaceAll("\\[[^\\]]+/[^\\]]+\\]", ""); parse = AnalysisUtilities.getInstance().readTreeFromString(ps); parseScore = parser.getPCFGScore(); return new arkref.parsestuff.AnalysisUtilities.ParseResult(true, parse, parseScore); } } catch (Exception e) { } parse = readTreeFromString("(ROOT (. .))"); parseScore = -99999.0; return new arkref.parsestuff.AnalysisUtilities.ParseResult(false, parse, parseScore); }