Example usage for java.net Socket shutdownOutput

List of usage examples for java.net Socket shutdownOutput

Introduction

In this page you can find the example usage for java.net Socket shutdownOutput.

Prototype

public void shutdownOutput() throws IOException 

Source Link

Document

Disables the output stream for this socket.

Usage

From source file:info.varden.irclinqed.dcc.FileReceiveThread.java

@Override
public void run() {
    try {/*ww  w  .  jav  a 2s  .  com*/
        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:com.jredrain.startup.Bootstrap.java

/**
 *
 * @throws Exception//w ww  .  ja  v a  2 s  . c  o m
 */

private void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command
     */
    Socket socket = new Socket("localhost", RedrainProperties.getInt("redrain.shutdown"));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    pw.write(shutdown);
    pw.flush();
    socket.shutdownOutput();
    String reply = null;
    while (!((reply = br.readLine()) == null)) {
        logger.info("[redrain]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}

From source file:org.opencron.agent.Bootstrap.java

/**
 *
 * @throws Exception//w  w w .jav a  2 s. com
 */

private void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command
     */
    Socket socket = new Socket("localhost", AgentProperties.getInt("opencron.shutdown"));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    pw.write(shutdown);
    pw.flush();
    socket.shutdownOutput();
    String reply = null;
    while (!((reply = br.readLine()) == null)) {
        logger.info("[opencron]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}

From source file:info.varden.irclinqed.dcc.FileSendThread.java

@Override
public void onIPSelected(String ipAddress) {
    try {/* ww  w.jav a2s. co  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   w  ww  .  java  2  s  .  co 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:com.example.will.sendpic.Camera2BasicFragment.java

private String sendFileGetResult(File file, String url, int port, int secTimeout) {
    Socket s = new Socket();
    String res = "Fail";

    try {//w ww  .j a  v a2 s  . c o  m
        s.connect(new InetSocketAddress(url, port), secTimeout * 1000);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] sendBytes = new byte[1024 * 4];
        int len = 0;

        while ((len = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
            dos.write(sendBytes, 0, len);
            dos.flush();
        }
        s.shutdownOutput();

        //get the result from server
        //you can change the protocol
        InputStream in = s.getInputStream();
        byte[] result = new byte[1024];
        int num = in.read(result);

        res = new String(result, 0, num);
        System.out.println(res);

        //closing resources
        s.close();
        dos.close();
        fis.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

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  . j  av a 2 s.  c  o m
            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:com.symbian.driver.core.controller.tasks.TEFTask.java

/**
 * @param aVisitor//from   w w  w  .  j a  v  a 2 s  .c  om
 * @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;
}