List of usage examples for java.net Socket shutdownOutput
public void shutdownOutput() 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 ww w .ja v a 2s . co m int c; while ((c = in.read()) != -1) { System.out.print((char) c); } s.shutdownInput(); s.shutdownOutput(); s.close(); }
From source file:cloudclient.Client.java
public static void main(String[] args) throws Exception { //Command interpreter CommandLineInterface cmd = new CommandLineInterface(args); String socket = cmd.getOptionValue("s"); String Host_IP = socket.split(":")[0]; int Port = Integer.parseInt(socket.split(":")[1]); String workload = cmd.getOptionValue("w"); try {// www . java 2 s. c om // make connection to server socket Socket client = new Socket(Host_IP, Port); InputStream inStream = client.getInputStream(); OutputStream outStream = client.getOutputStream(); PrintWriter out = new PrintWriter(outStream, true); BufferedReader in = new BufferedReader(new InputStreamReader(inStream)); System.out.println("Send tasks to server..."); //Start clock long startTime = System.currentTimeMillis(); //Batch sending tasks batchSendTask(out, workload); client.shutdownOutput(); //Batch receive responses batchReceiveResp(in); //End clock long endTime = System.currentTimeMillis(); double totalTime = (endTime - startTime) / 1e3; System.out.println("\nDone!"); System.out.println("Time to execution = " + totalTime + " sec."); // close the socket connection client.close(); } catch (IOException ioe) { System.err.println(ioe); } }
From source file:org.msec.TestClient.java
public static void main(String[] args) { Options options = new Options(); Option option = new Option("t", "type", true, "the type of this request: query/add/del/get/graph"); option.setRequired(true);/*w w w . j a v a2 s . co m*/ options.addOption(option); option = new Option("f", "field", true, "required if add field or del field"); option.setRequired(false); options.addOption(option); option = new Option("h", "help", false, "show help"); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.out.println("Parse command line failed."); e.printStackTrace(); return; } if (commandLine.hasOption('h')) { new HelpFormatter().printHelp("LogsysProxy Client", options, true); return; } String reqType = commandLine.getOptionValue('t'); String fieldName = commandLine.getOptionValue("f"); if (!reqType.equals("query") && !reqType.equals("add") && !reqType.equals("del") && !reqType.equals("get") && !reqType.equals("graph")) { System.out.println("Invalid type " + reqType); return; } if ((reqType.equals("add") || reqType.equals("del")) && (fieldName == null || fieldName.isEmpty())) { System.out.println("No fieldname specified."); return; } try { Socket socket = new Socket("localhost", 30150); OutputStream os = socket.getOutputStream(); // org.msec.LogsysReq req = new org.msec.LogsysReq(); if (reqType.equals("query")) { req.queryLogReq = new org.msec.LogsysReq.QueryLogReq(); setRequest(req.queryLogReq); } if (reqType.equals("add")) { req.modifyFieldsReq = new org.msec.LogsysReq.ModifyFieldsReq(); req.modifyFieldsReq.setAppName("App"); req.modifyFieldsReq.setFieldName(fieldName); req.modifyFieldsReq.setFieldType("String"); req.modifyFieldsReq.setOperator("ADD"); } if (reqType.equals("del")) { req.modifyFieldsReq = new org.msec.LogsysReq.ModifyFieldsReq(); req.modifyFieldsReq.setAppName("TestApp"); req.modifyFieldsReq.setFieldName(fieldName); req.modifyFieldsReq.setFieldType("String"); req.modifyFieldsReq.setOperator("DEL"); } if (reqType.equals("get")) { req.getFieldsReq = new org.msec.LogsysReq.GetFieldsReq(); req.getFieldsReq.setAppName("TestApp"); } if (reqType.equals("graph")) { req.callGraphReq = new org.msec.LogsysReq.CallGraphReq(); req.callGraphReq.setAppName("JavaSample.Jecho"); //req.callGraphReq.addFilterField(new LogField("RPCName", "", "rpc814")); req.callGraphReq.setStartDate("2016-07-04"); req.callGraphReq.setEndDate("2016-07-04"); req.callGraphReq.setStartTime("00:00:00"); req.callGraphReq.setEndTime("23:59:00"); } ObjectMapper objectMapper = new ObjectMapper(); String reqJsonStr = objectMapper.writeValueAsString(req); String reqJsonLen = String.format("%-10d", reqJsonStr.length()); System.out.println(reqJsonLen + reqJsonStr); os.write(reqJsonLen.getBytes()); os.write(reqJsonStr.getBytes()); socket.shutdownOutput(); // InputStream is = socket.getInputStream(); byte[] buff = new byte[1024]; int readLen = 0; // while ((readLen = is.read(buff)) > 0) { System.out.println(new String(buff)); } is.close(); os.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.sharneng.net.NetUtils.java
/** * Quietly shutdown the output of a {@linkplain Socket}. Exceptions are ignored. * /*from ww w .j a v a 2 s . c o m*/ * @param socket * the socket to shutdown the output * @see Socket#shutdownOutput() */ public static void shutdownOutput(Socket socket) { if (socket == null) return; try { if (!socket.isOutputShutdown()) socket.shutdownOutput(); } catch (Throwable e) { log.debug(e.getMessage(), e); } }
From source file:com.linkedin.d2.quorum.ZKPeer.java
/** * Send the 4letterword/*from ww w. j av a 2s . co m*/ * * @param host- destination host * @param port- destination port * @param cmd- the 4letterword (stat, srvr,etc. - see * http://zookeeper.apache.org/doc/r3.3.3/zookeeperAdmin.html#sc_zkCommands) * @return * @throws IOException */ public static String sendCommand(String host, int port, String cmd) throws IOException { // NOTE: ignore CancelledKeyException in logs caused by // https://issues.apache.org/jira/browse/ZOOKEEPER-1237 Socket sock = new Socket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write(cmd.getBytes()); outstream.flush(); sock.shutdownOutput(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } finally { sock.close(); if (reader != null) { reader.close(); } } }
From source file:org.java.plugin.boot.ControlThread.java
static boolean stopRunningApplication(final InetAddress host, final int port) { boolean result = false; try {// w ww.j a v a 2s . c om 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 ww w. ja v a 2s. c om*/ 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:org.kuali.rice.edl.framework.workflow.EDocLitePostProcessor.java
/** * @param urlstring//w w w. java 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:VASSAL.launch.TilingHandler.java
protected void runSlicer(List<String> multi, final int tcount, int maxheap) throws CancellationException, IOException { final InetAddress lo = InetAddress.getByName(null); final ServerSocket ssock = new ServerSocket(0, 0, lo); final int port = ssock.getLocalPort(); final List<String> args = new ArrayList<String>(); args.addAll(Arrays.asList(new String[] { Info.javaBinPath, "-classpath", System.getProperty("java.class.path"), "-Xmx" + maxheap + "M", "-DVASSAL.id=" + pid, "-Duser.home=" + System.getProperty("user.home"), "-DVASSAL.port=" + port, "VASSAL.tools.image.tilecache.ZipFileImageTiler", aname, cdir.getAbsolutePath(), String.valueOf(tdim.width), String.valueOf(tdim.height) })); // get the progress dialog final ProgressDialog pd = ProgressDialog.createOnEDT(ModuleManagerWindow.getInstance(), "Processing Image Tiles", " "); // set up the process final InputStreamPump outP = new InputOutputStreamPump(null, System.out); final InputStreamPump errP = new InputOutputStreamPump(null, System.err); final ProcessWrapper proc = new ProcessLauncher().launch(null, outP, errP, args.toArray(new String[args.size()])); // write the image paths to child's stdin, one per line PrintWriter stdin = null;//ww w . j av a 2 s .c o m try { stdin = new PrintWriter(proc.stdin); for (String m : multi) { stdin.println(m); } } finally { IOUtils.closeQuietly(stdin); } Socket csock = null; DataInputStream in = null; try { csock = ssock.accept(); csock.shutdownOutput(); in = new DataInputStream(csock.getInputStream()); final Progressor progressor = new Progressor(0, tcount) { @Override protected void run(Pair<Integer, Integer> prog) { pd.setProgress((100 * prog.second) / max); } }; // setup the cancel button in the progress dialog EDT.execute(new Runnable() { public void run() { pd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pd.setVisible(false); proc.future.cancel(true); } }); } }); boolean done = false; byte type; while (!done) { type = in.readByte(); switch (type) { case STARTING_IMAGE: final String ipath = in.readUTF(); EDT.execute(new Runnable() { public void run() { pd.setLabel("Tiling " + ipath); if (!pd.isVisible()) pd.setVisible(true); } }); break; case TILE_WRITTEN: progressor.increment(); if (progressor.get() >= tcount) { pd.setVisible(false); } break; case TILING_FINISHED: done = true; break; default: throw new IllegalStateException("bad type: " + type); } } in.close(); csock.close(); ssock.close(); } catch (IOException e) { } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(csock); IOUtils.closeQuietly(ssock); } // wait for the tiling process to end try { final int retval = proc.future.get(); if (retval != 0) { throw new IOException("return value == " + retval); } } catch (ExecutionException e) { // should never happen throw new IllegalStateException(e); } catch (InterruptedException e) { // should never happen throw new IllegalStateException(e); } }
From source file:org.apache.batchee.cli.command.SocketCommand.java
protected void sendCommand() { if (adminSocket < 0) { throw new BatchContainerRuntimeException("specify -socket to be able to run this command"); }//from w ww . j av a 2s. c o m Socket socket = null; try { socket = new Socket("localhost", adminSocket); socket.setSoTimeout(timeout); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Integer> answer = new AtomicReference<Integer>(); new AnswerThread(socket, answer, latch).start(); final OutputStream outputStream = socket.getOutputStream(); outputStream.write(command().getBytes()); outputStream.flush(); socket.shutdownOutput(); try { latch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { info("no answer after " + timeout + "ms"); return; } if (answer.get() != 0) { info("unexpected answer: " + answer.get()); } } catch (final IOException e) { throw new BatchContainerRuntimeException(e); } finally { IOUtils.closeQuietly(socket); } }