List of usage examples for java.net Socket shutdownInput
public void shutdownInput() throws IOException
From source file:Main.java
License:asdf
public static void main(String args[]) throws Exception { Socket s = new Socket("internic.net", 43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str = "asdfasdfasdf\n"; byte buf[] = str.getBytes(); out.write(buf);//from w w w .ja va2 s. c o m int c; while ((c = in.read()) != -1) { System.out.print((char) c); } s.shutdownInput(); s.shutdownOutput(); s.close(); }
From source file:com.sharneng.net.NetUtils.java
/** * Quietly shutdown the input of a {@linkplain Socket}. Exception are ignored. * //from w w w . j a v a 2 s.c om * @param socket * the socket to shutdown the input */ public static void shutdownInput(Socket socket) { if (socket == null) return; try { if (!socket.isInputShutdown()) socket.shutdownInput(); } catch (Throwable e) { log.debug(e.getMessage(), e); } }
From source file:org.java.plugin.boot.ControlThread.java
static boolean stopRunningApplication(final InetAddress host, final int port) { boolean result = false; try {//w w w. j a va 2 s . c o m Socket socket = new Socket(host, port); try { socket.setKeepAlive(true); OutputStream out = socket.getOutputStream(); InputStream in = null; try { System.out.println("found running control service on " //$NON-NLS-1$ + host + ":" + port); //$NON-NLS-1$ out.write("STOP".getBytes()); //$NON-NLS-1$ out.flush(); socket.shutdownOutput(); in = socket.getInputStream(); StringBuilder commandResult = new StringBuilder(); byte[] buf = new byte[16]; int len; while ((len = in.read(buf)) != -1) { commandResult.append(new String(buf, 0, len)); } socket.shutdownInput(); if (commandResult.toString().startsWith("OK")) { //$NON-NLS-1$ System.out.println("STOP command succeed"); //$NON-NLS-1$ result = true; } else { System.out.println("STOP command failed"); //$NON-NLS-1$ } } finally { try { out.close(); } catch (IOException ioe) { // ignore } if (in != null) { try { in.close(); } catch (IOException ioe) { // ignore } } } } finally { socket.close(); } } catch (IOException ioe) { System.out.println("seems that there is no control service running on " //$NON-NLS-1$ + host + ":" + port); //$NON-NLS-1$ //ioe.printStackTrace(); } if (result) { try { Thread.sleep(2000); } catch (InterruptedException ie) { // ignore } } return result; }
From source file:org.java.plugin.boot.ControlThread.java
static boolean isApplicationRunning(final InetAddress host, final int port) { try {/*from w w w . j a va 2 s. c o m*/ Socket socket = new Socket(host, port); try { socket.setKeepAlive(true); String test = "" + System.currentTimeMillis(); //$NON-NLS-1$ OutputStream out = socket.getOutputStream(); InputStream in = null; try { System.out.println("found running control service on " //$NON-NLS-1$ + host + ":" + port); //$NON-NLS-1$ out.write(("PING " + test).getBytes()); //$NON-NLS-1$ out.flush(); socket.shutdownOutput(); in = socket.getInputStream(); StringBuilder commandResult = new StringBuilder(); byte[] buf = new byte[16]; int len; while ((len = in.read(buf)) != -1) { commandResult.append(new String(buf, 0, len)); } socket.shutdownInput(); if (commandResult.toString().startsWith("OK") //$NON-NLS-1$ && (commandResult.toString().indexOf(test) != -1)) { System.out.println("PING command succeed"); //$NON-NLS-1$ return true; } System.out.println("PING command failed"); //$NON-NLS-1$ } finally { try { out.close(); } catch (IOException ioe) { // ignore } if (in != null) { try { in.close(); } catch (IOException ioe) { // ignore } } } } finally { socket.close(); } } catch (IOException ioe) { System.out.println("seems that there is no control service running on " //$NON-NLS-1$ + host + ":" + port); //$NON-NLS-1$ //ioe.printStackTrace(); } return false; }
From source file:info.varden.irclinqed.dcc.FileReceiveThread.java
@Override public void run() { try {//from w w w. j av a 2 s .co m this.il.keyListenerQueue.add(this); this.gfp = new GuiFileProgress(this.packet.il, this); this.packet.il.guiQueue.add(this.gfp); if (!this.file.getParentFile().exists()) { this.file.getParentFile().mkdirs(); } if (!this.file.exists()) { this.file.createNewFile(); } Socket s = new Socket(this.host, this.port); InputStream i = s.getInputStream(); this.cos = new CountingOutputStream(new FileOutputStream(this.file)); byte[] buff = new byte[1024]; int k = -1; while ((k = i.read(buff)) > -1 && !this.cancel) { this.cos.write(buff, 0, k); s.getOutputStream().write(ByteBuffer.allocate(4).putInt((int) getByteCount()).array()); } s.shutdownInput(); s.shutdownOutput(); s.close(); this.cos.close(); this.gfp.unload(); } catch (IOException e) { e.printStackTrace(); } }
From source file:info.varden.irclinqed.dcc.FileSendThread.java
@Override public void onIPSelected(String ipAddress) { try {// ww w . ja v a 2 s . c o m if (!this.file.exists()) { return; } this.server = new ServerSocket(0); this.server.setSoTimeout(60000); DCCRequestPacket packet = null; String filename = this.file.getName(); if (filename.split(" ").length > 1) { filename = "\"" + filename + "\""; } if (this.thread instanceof IRCThread) { packet = new DCCRequestPacket(this.il, (IRCThread) this.thread, this.target, DCCType.SEND, filename, ipAddress, server.getLocalPort(), this.totalSize); } else if (this.thread instanceof DCCThread) { VirtualIRCThread thrd = new VirtualIRCThread(this.il, (DCCThread) this.thread); packet = new DCCRequestPacket(this.il, thrd, this.target, DCCType.SEND, filename, ipAddress, server.getLocalPort(), this.totalSize); } else { this.server.close(); return; } packet.send(); if (this.cancel) { this.server.close(); return; } this.message = "Waiting for connection..."; Socket s = this.server.accept(); this.overlay.unload(); this.gfp = new GuiFileProgress(this.il, this); this.il.guiQueue.add(this.gfp); InputStream i = new FileInputStream(this.file); this.cos = new CountingOutputStream(s.getOutputStream()); byte[] buff = new byte[1024]; int k = -1; while ((k = i.read(buff)) > -1 && !this.cancel) { this.cos.write(buff, 0, k); s.getInputStream().read(new byte[4]); } s.shutdownInput(); s.shutdownOutput(); s.close(); this.server.close(); i.close(); this.gfp.unload(); } catch (SocketTimeoutException e) { this.overlay.unload(); Util.extractUtil(this.thread).writeToChat(MessageType.DCC_ERROR, "File send timed out."); } catch (IOException e) { e.printStackTrace(); } this.overlay.unload(); }
From source file:com.clough.android.adbv.manager.ADBManager.java
/** * Waiting for a device to connect and connect with it's one of eligible * android application for AndroidDBViewer to run. * @return IOManager instance configured for a android application * @throws IOException//from www . j a va2s .c o m * @throws ADBManagerException */ public IOManager makeConnection() throws IOException, ADBManagerException { // Placing adb executable files for the desktop application use placeRelevantAdb(); // Trying to connect with android application again and agian // when ever an attempt is fail while (true) { try { // Creating a socket with PC_PORT and trying to connect with an server socket. // Connecting can fails due the ports not being forwarded or due to the // server socket not being started yet. // To be able to detect the server socket as running, a device must connected to the PC // and ADBVApplication configured android app must run on the device. final Socket deviceSocket = new Socket("localhost", PC_PORT); // Requesting to connect new PrintWriter(deviceSocket.getOutputStream(), true) .println(new Data(Data.CONNECTION_REQUEST, "", "").toJSON().toString()); Data recivedData = new Data(new JSONObject( new BufferedReader(new InputStreamReader(deviceSocket.getInputStream())).readLine())); if (recivedData.getStatus() == Data.CONNECTION_ACCEPTED) { // Adding a shudown hook to disconnect the adb connection and close the socket connection Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { killServer(); try { deviceSocket.shutdownInput(); deviceSocket.shutdownOutput(); deviceSocket.close(); } catch (IOException ex) { } } })); // Returning an IOManager created for this connection return new IOManager(deviceSocket); } } catch (IOException ex) { prepareADB(); } catch (NullPointerException ex) { prepareADB(); } catch (JSONException ex) { prepareADB(); } } }
From source file:org.java.plugin.boot.ControlThread.java
private synchronized boolean handleRequest(final Socket clientSocket) { debug("handling control request"); //$NON-NLS-1$ if (!isValidRemoteHost(clientSocket.getInetAddress())) { warn("incoming connection to control socket registered" //$NON-NLS-1$ + " from REMOTE address " + clientSocket.getInetAddress() //$NON-NLS-1$ + ", attempt to execute command was IGNORED"); //$NON-NLS-1$ try {/* w w w .ja v a 2 s .c om*/ clientSocket.close(); } catch (IOException e) { // ignore } return false; } debug("processing control request"); //$NON-NLS-1$ boolean result = false; try { String commandResult; InputStream in = clientSocket.getInputStream(); OutputStream out = null; try { StringBuilder command = new StringBuilder(); byte[] buf = new byte[16]; int len; while ((len = in.read(buf)) != -1) { command.append(new String(buf, 0, len)); } clientSocket.shutdownInput(); debug("got command - " + command); //$NON-NLS-1$ if ("STOP".equals(command.toString())) { //$NON-NLS-1$ stopApplication(); result = true; commandResult = "OK: stop done"; //$NON-NLS-1$ } else if (command.toString().startsWith("PING")) { //$NON-NLS-1$ commandResult = "OK: " //$NON-NLS-1$ + command.substring("PING".length()); //$NON-NLS-1$ } else { commandResult = "ERROR: unknown command"; //$NON-NLS-1$ } //debug("command executed"); //debug("sending command result - " + commandResult); out = clientSocket.getOutputStream(); out.write(commandResult.getBytes()); out.flush(); clientSocket.shutdownOutput(); //debug("command result sent"); } finally { try { in.close(); } catch (IOException ioe) { // ignore } if (out != null) { try { out.close(); } catch (IOException ioe) { // ignore } } } } catch (IOException ioe) { error("error processing control request", ioe); //$NON-NLS-1$ } return result; }
From source file:org.kuali.rice.edl.framework.workflow.EDocLitePostProcessor.java
/** * @param urlstring/*from w w w . j a v a 2s .co m*/ * @param eventDoc */ private static void submitURL(String urlstring, Document eventDoc) throws IOException { String content; try { content = XmlJotter.jotNode(eventDoc, true); } catch (XmlException te) { LOG.error("Error writing serializing event doc: " + eventDoc); throw te; } byte[] contentBytes = content.getBytes("UTF-8"); LOG.debug("submitURL: " + urlstring); URL url = new URL(urlstring); String message = "POST " + url.getFile() + " HTTP/1.0\r\n" + "Content-Length: " + contentBytes.length + "\r\n" + "Cache-Control: no-cache\r\n" + "Pragma: no-cache\r\n" + "User-Agent: Java/1.4.2; EDocLitePostProcessor\r\n" + "Host: " + url.getHost() + "\r\n" + "Connection: close\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n\r\n" + content; byte[] buf = message.getBytes("UTF-8"); Socket s = new Socket(url.getHost(), url.getPort()); /*URLConnection con = url.openConnection(); LOG.debug("got connection: " + con); con.setDoOutput(true); con.setDoInput(true); LOG.debug("setDoOutput(true)"); con.setRequestProperty("Connection", "close"); con.setRequestProperty("Content-Length", String.valueOf(buf.length));*/ OutputStream os = s.getOutputStream(); try { try { os.write(buf, 0, buf.length); os.flush(); } catch (InterruptedIOException ioe) { LOG.error("IO was interrupted while posting event to url " + urlstring + ": " + ioe.getMessage()); } catch (IOException ioe) { LOG.error("Error posting EDocLite content to url " + urlstring + ioe.getMessage()); } finally { try { LOG.debug("Shutting down output stream"); s.shutdownOutput(); } catch (IOException ioe) { LOG.error("Error shutting down output stream for url " + urlstring + ": " + ioe.getMessage()); } } InputStream is = s.getInputStream(); try { buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); // this is what actually forces the write on the URLConnection! int read = is.read(buf); if (read != -1) { baos.write(buf, 0, read); } LOG.debug("EDocLite post processor response:\n" + new String(baos.toByteArray())); } catch (InterruptedIOException ioe) { LOG.error("IO was interrupted while reading response from url " + urlstring + ": " + ioe.getMessage()); } catch (IOException ioe) { LOG.error("Error reading response from EDocLite handler url " + urlstring + ioe.getMessage()); } finally { try { LOG.debug("Shutting down input stream"); s.shutdownInput(); } catch (IOException ioe) { LOG.error("Error shutting down input stream for url " + urlstring + ": " + ioe.getMessage()); } } } finally { try { s.close(); } catch (IOException ioe) { LOG.error("Error closing socket", ioe); } } }
From source file:com.symbian.driver.core.controller.tasks.TEFTask.java
/** * @param aVisitor/*from ww w .j ava 2 s.co m*/ * @param aTestExecuteScript * @param lExecuteOnDevice * @param aTask * @return The last execption raised when running UCC. * @throws JStatException */ private boolean runUCC(List<String> aArgs, Task aTask) { boolean lReturn = true; Socket lUccSocket = null; DataOutputStream lSocketOut = null; DataInputStream lSocketIn = null; int lRunNumber = 0; int lUccPort = -1; String lUccAddress = null; IDeviceComms.ISymbianProcess lProcess = null; try { String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":"); lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER); lUccAddress = lUccSplit[0]; lUccPort = Integer.parseInt(lUccSplit[1]); } catch (ParseException lParseException) { LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException); iExceptions.put(lParseException, ESeverity.ERROR); lReturn = false; } catch (NumberFormatException lNumberFormatException) { LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException); iExceptions.put(lNumberFormatException, ESeverity.ERROR); lReturn = false; } if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) { iExceptions.put( new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"), ESeverity.ERROR); return false; } // Run the test try { LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort); lUccSocket = new Socket(lUccAddress, lUccPort); lSocketOut = new DataOutputStream(lUccSocket.getOutputStream()); lSocketIn = new DataInputStream(lUccSocket.getInputStream()); LOGGER.fine("Starting UCC while still polling"); lProcess = iDeviceProxy.createSymbianProcess(); if (lProcess != null) { // run and don't wait if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) { iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR); lReturn = false; } // Tell UCC that the test has started. LOGGER.fine("Writing to UCC socket: " + lRunNumber); lSocketOut.writeInt(lRunNumber); lSocketOut.flush(); int lUCCReply = lSocketIn.readInt(); LOGGER.fine("UCC Reply: " + lUCCReply); } } catch (UnknownHostException lUnknownHostException) { LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException); iExceptions.put(lUnknownHostException, ESeverity.ERROR); return false; } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: " + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:" + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound() : "\nUcc Socket is NULL"), lIOException); iExceptions.put(lIOException, ESeverity.ERROR); return false; } finally { // Close UCC if (lSocketOut != null) { try { LOGGER.log(Level.FINE, "Closing Socket Out."); lUccSocket.shutdownInput(); lUccSocket.shutdownOutput(); lSocketOut.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (lSocketIn != null) { try { LOGGER.log(Level.FINE, "Closing Socket In."); lSocketIn.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (lUccSocket != null) { try { LOGGER.log(Level.FINE, "Closing Socket UCC."); lUccSocket.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (!lUccSocket.isClosed()) { LOGGER.warning("Could not close the UCC sockets properly."); } lSocketOut = null; lSocketIn = null; lUccSocket = null; // Poll TEF Test if (!lProcess.join()) { iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR); lReturn = false; } } return lReturn; }