Example usage for java.net Socket close

List of usage examples for java.net Socket close

Introduction

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

Prototype

public synchronized void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:com.photon.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   w w  w.  j  a  v  a 2s  . co  m*/
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:org.jfree.chart.demo.SocketThread.java

@Override
public void run() {
    // TODO Auto-generated method stub
    try {//from www.j  a v a  2  s .  c  o m
        ServerSocket ss = new ServerSocket(4444);
        Socket socket = null;
        while (Islive) {
            System.out.println("Started :) ");
            socket = ss.accept(); /*  */
            System.out.println("Got a client :) ");

            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();

            in = new DataInputStream(sin);
            out = new DataOutputStream(sout);

            String line = null;

            while (true) {
                line = in.readUTF(); /*    */
                System.out.println("line start sending  = " + line);
                out.writeUTF(data);
                out.flush();
                line = in.readUTF();
                System.out.println(line);
                if (line == "finish")
                    break;
                else {
                    out.writeUTF("ok");
                    out.flush();
                }
            }
        }
        out.writeUTF("finish");
        out.flush();

        in.close();
        out.close();
        socket.close();
    } catch (Exception x) {

        errors += x.toString() + " ;\n";
        error_flag = true;
    }

}

From source file:bankingclient.DKFrame.java

public DKFrame(MainFrame vmain) {
    initComponents();/*from   w  ww .  j a  va  2  s  . c om*/
    this.main = vmain;
    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField3.setText("");
    this.jTextField4.setText("");
    this.jTextField5.setText("");
    this.setVisible(false);
    jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jTextField2.getText().equals(jTextField3.getText())
                    && NumberUtils.isNumber(jTextField4.getText())
                    && NumberUtils.isNumber(jTextField5.getText())) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    String cusName = jTextField1.getText();
                    String pass = jTextField2.getText();
                    String sdt = jTextField4.getText();
                    String cmt = jTextField5.getText();
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(1);
                    dout.writeUTF(cusName + "\n" + pass + "\n" + sdt + "\n" + cmt);
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da dang ki tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "dang ki tai khoan khong thanh cong");

                    }
                    client.close();
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
                main.setVisible(true);
                DKFrame.this.setVisible(false);

            } else {
                JOptionPane.showMessageDialog(rootPane, "Nhap thong tin sai, moi nhap lai");
            }
        }
    });
    jButton2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DKFrame.this.setVisible(false);
        }
    });
}

From source file:infosistema.openbaas.rest.IntegrationResource.java

@Path("/test4")
@POST//from w  ww  .j a  va2 s .c o m
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response test4(JSONObject inputJsonObj, @Context UriInfo ui, @Context HttpHeaders hh)
        throws IOException {
    String everything = "";
    BufferedReader br = new BufferedReader(new FileReader("/home/aniceto/baas/file2000x2000.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        everything = sb.toString();
    } finally {
        br.close();
    }

    Socket echoSocket = null;
    try {
        echoSocket = new Socket("askme2.cl.infosistema.com", 4005);
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);

        //StringBuffer str = new StringBuffer((String) inputJsonObj.get("str"));

        //String s = str.toString();//"/// DEVES COLOCAR AQUI A IMAGEM SERIALIZADA COM Base64";
        String s = everything;
        byte[] c = s.getBytes();
        echoSocket.getOutputStream().write(c);
        out.flush();
        s = "\n";
        c = s.getBytes();
        echoSocket.getOutputStream().write(c);
        out.flush();
        System.out.println("OK");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            echoSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return Response.status(Status.OK).entity("DEL OK").build();
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 *//*  w  ww  .  ja  va  2 s .c o  m*/
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

        return localIp;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;
    DataOutputStream os = null;/*from   ww w .j  ava 2 s . c  o m*/
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

private void sendTcpMsg(InetAddress ipAddress, int port, String msg) throws IOException {

    Socket socket = null;
    OutputStream os = null;// w  ww .j  av a 2s .  c o  m
    PrintWriter writer = null;
    try {
        InetSocketAddress endpoint = new InetSocketAddress(ipAddress, port);
        socket = new Socket();
        socket.connect(endpoint,
                HinemosPropertyUtil.getHinemosPropertyNum(PROP_TCP_TIMEOUT, Long.valueOf(3000)).intValue());

        os = socket.getOutputStream();
        writer = new PrintWriter(socket.getOutputStream(), true);
        writer.println(msg);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (os != null) {
            os.close();
        }
        if (socket != null) {
            socket.close();
        }
    }
}

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 ww w .  ja  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:net.jotel.ws.client.WebSocketClient.java

public void close() throws WebSocketException {
    synchronized (sync) {
        // Once a WebSocket connection is established, the user agent must
        // use the following steps to *start the WebSocket closing
        // handshake*. These steps must be run asynchronously relative to
        // whatever algorithm invoked this one.

        // 1. If the WebSocket closing handshake has started, then abort
        // these steps.
        if (isClosed()) {
            return;
        }//  ww  w  .  j a  v a  2  s  .c o m

        try {
            if (keepAliveThread != null) {
                keepAliveThread.interrupt();
                keepAliveThread = null;
            }

            if (isConnected()) {
                try {
                    startClosingHandshake();

                    // 5. Wait a user-agent-determined length of time, or
                    // until the WebSocket connection is closed.
                    try {
                        readerThread.join(closingHandshakeTimeout);
                    } catch (InterruptedException ex) {
                        // ignore
                    }
                } finally {
                    closingHandshakeStarted = false;

                    if (readerThread.isAlive()) {
                        log.debug("WebSocketReader Thread still alive");
                        readerThread.finish();
                        readerThread.interrupt();
                    }

                    readerThread = null;

                    // 6. If the WebSocket connection is not already closed,
                    // then close the WebSocket connection. (If this
                    // happens, then the closing handshake doesn't finish.)
                    log.debug("Closing the WebSocket connection");
                    Socket s = socket;
                    socket = null;
                    s.close();
                }
            }
        } catch (IOException ex) {
            throw new WebSocketException(ex);
        } finally {
            // NOTE: The closing handshake finishes once the server returns
            // the 0xFF packet, as described above.
            closed = true;
        }
    }
}