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:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test that by default we have protocol version 1.4.
 * //from w ww .jav  a2 s .c o m
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testDefault() throws Exception {
    final Agent agent = new ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("system.property[java.version]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);
    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:com.sun.grizzly.http.jk.common.ChannelSocket.java

public void close(MsgContext ep) throws IOException {
    Socket s = (Socket) ep.getNote(socketNote);
    s.close();
}

From source file:com.neophob.sematrix.listener.TcpServer.java

/**
 * Connect to client./*from   www. java2 s.  com*/
 */
private void connectToClient() {
    Socket socket = new Socket();
    lastConnectTimestamp = System.currentTimeMillis();
    try {
        socket.connect(new InetSocketAddress(sendHost, sendPort), 2000);
        client = new Client(app, socket);
        LOG.log(Level.INFO, "Pure Data Client connected at " + sendHost + ":" + sendPort + "!");
        pdClientConnected = true;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Pure Data Client not found at " + sendHost + ":" + sendPort);
        pdClientConnected = false;
        client = null;
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e2) {
            }
        }
    }
}

From source file:hudson.remoting.Engine.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
@Override/*from  w w  w . j a  v  a  2 s. c  o  m*/
public void run() {
    try {
        boolean first = true;
        while (true) {
            if (first) {
                first = false;
            } else {
                if (noReconnect)
                    return; // exit
            }

            listener.status("Locating server among " + candidateUrls);
            Throwable firstError = null;
            String port = null;

            for (URL url : candidateUrls) {
                String s = url.toExternalForm();
                if (!s.endsWith("/"))
                    s += '/';
                URL salURL = new URL(s + "tcpSlaveAgentListener/");

                // find out the TCP port
                HttpURLConnection con = (HttpURLConnection) salURL.openConnection();
                if (con instanceof HttpURLConnection && credentials != null) {
                    String encoding = new String(Base64.encodeBase64(credentials.getBytes()));
                    con.setRequestProperty("Authorization", "Basic " + encoding);
                }
                try {
                    try {
                        con.setConnectTimeout(30000);
                        con.setReadTimeout(60000);
                        con.connect();
                    } catch (IOException x) {
                        if (firstError == null) {
                            firstError = new IOException(
                                    "Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x);
                        }
                        continue;
                    }
                    port = con.getHeaderField("X-Hudson-JNLP-Port");
                    if (con.getResponseCode() != 200) {
                        if (firstError == null)
                            firstError = new Exception(salURL + " is invalid: " + con.getResponseCode() + " "
                                    + con.getResponseMessage());
                        continue;
                    }
                    if (port == null) {
                        if (firstError == null)
                            firstError = new Exception(url + " is not Hudson");
                        continue;
                    }
                } finally {
                    con.disconnect();
                }

                // this URL works. From now on, only try this URL
                hudsonUrl = url;
                firstError = null;
                candidateUrls = Collections.singletonList(hudsonUrl);
                break;
            }

            if (firstError != null) {
                listener.error(firstError);
                return;
            }

            Socket s = connect(port);

            listener.status("Handshaking");

            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(s.getInputStream());

            dos.writeUTF("Protocol:JNLP2-connect");
            Properties props = new Properties();
            props.put("Secret-Key", secretKey);
            props.put("Node-Name", slaveName);
            if (cookie != null)
                props.put("Cookie", cookie);
            ByteArrayOutputStream o = new ByteArrayOutputStream();
            props.store(o, null);
            dos.writeUTF(o.toString("UTF-8"));

            String greeting = readLine(in);
            if (greeting.startsWith("Unknown protocol")) {
                LOGGER.info("The server didn't understand the v2 handshake. Falling back to v1 handshake");
                s.close();
                s = connect(port);
                in = new BufferedInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());

                dos.writeUTF("Protocol:JNLP-connect");
                dos.writeUTF(secretKey);
                dos.writeUTF(slaveName);

                greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network?
                if (!greeting.equals(GREETING_SUCCESS)) {
                    onConnectionRejected(greeting);
                    continue;
                }
            } else {
                if (greeting.equals(GREETING_SUCCESS)) {
                    Properties responses = readResponseHeaders(in);
                    cookie = responses.getProperty("Cookie");
                } else {
                    onConnectionRejected(greeting);
                    continue;
                }
            }

            final Socket socket = s;
            final Channel channel = new Channel("channel", executor, in,
                    new BufferedOutputStream(s.getOutputStream()));
            PingThread t = new PingThread(channel) {
                protected void onDead() {
                    try {
                        if (!channel.isInClosed()) {
                            LOGGER.info("Ping failed. Terminating the socket.");
                            socket.close();
                        }
                    } catch (IOException e) {
                        LOGGER.log(SEVERE, "Failed to terminate the socket", e);
                    }
                }
            };
            t.start();
            listener.status("Connected");
            channel.join();
            listener.status("Terminated");
            t.interrupt(); // make sure the ping thread is terminated
            listener.onDisconnect();

            if (noReconnect)
                return; // exit
            // try to connect back to the server every 10 secs.
            waitForServerToBack();
        }
    } catch (Throwable e) {
        listener.error(e);
    }
}

From source file:SendMail.java

/**
 * Called when the send button is clicked. Actually sends the mail message.
 * //from   w w  w. j  ava2  s . c  o  m
 * @param event
 *            The event.
 */
void Send_actionPerformed(java.awt.event.ActionEvent event) {
    try {

        java.net.Socket s = new java.net.Socket(_smtp.getText(), 25);
        _out = new java.io.PrintWriter(s.getOutputStream());
        _in = new java.io.BufferedReader(new java.io.InputStreamReader(s.getInputStream()));

        send(null);
        send("HELO " + java.net.InetAddress.getLocalHost().getHostName());
        send("MAIL FROM: " + _from.getText());
        send("RCPT TO: " + _to.getText());
        send("DATA");
        _out.println("Subject:" + _subject.getText());
        _out.println(_body.getText());
        send(".");
        s.close();

    } catch (Exception e) {
        _model.addElement("Error: " + e);
    }

}

From source file:MailTest.java

/**
 * Sends the mail message that has been authored in the GUI.
 *//*www .  ja v  a2 s  .  c  om*/
public void sendMail() {
    try {
        Socket s = new Socket(smtpServer.getText(), 25);

        InputStream inStream = s.getInputStream();
        OutputStream outStream = s.getOutputStream();

        in = new Scanner(inStream);
        out = new PrintWriter(outStream, true /* autoFlush */);

        String hostName = InetAddress.getLocalHost().getHostName();

        receive();
        send("HELO " + hostName);
        receive();
        send("MAIL FROM: <" + from.getText() + ">");
        receive();
        send("RCPT TO: <" + to.getText() + ">");
        receive();
        send("DATA");
        receive();
        send(message.getText());
        send(".");
        receive();
        s.close();
    } catch (IOException e) {
        comm.append("Error: " + e);
    }
}

From source file:bankingclient.TaoTaiKhoanFrame.java

public TaoTaiKhoanFrame(NewOrOldAccFrame acc) {

    initComponents();//from w  ww.  j  av a2s .  co m
    this.jText_ten_tk.setText("");
    this.jText_sd.setText("");

    this.noAcc = acc;
    this.mainCustomerName = null;
    this.setVisible(false);

    jBt_ht.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jText_sd.getText()) && (Long.parseLong(jText_sd.getText()) > 0)) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(3);
                    dout.writeUTF(jText_ten_tk.getText() + "\n" + mainCustomerName + "\n" + jText_sd.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da tao tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "tao tai khoan khong thanh cong");
                    }
                    client.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                noAcc.setVisible(true);
                TaoTaiKhoanFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane, "Can nhap lai so tien gui");
            }

        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            TaoTaiKhoanFrame.this.setVisible(false);

        }
    });
}

From source file:ie.deri.wsmx.core.management.httpadapter.HttpAdapter.java

/**
 * Starts the server//  w w w  .ja v  a 2s.co  m
 */
public void start() throws IOException {
    if (server != null) {
        serverSocket = createServerSocket();

        if (serverSocket == null) {
            logger.error("Server socket is null");
            return;
        }

        if (processorClass != null && processorName != null) {
            logger.debug("Building processor class of type " + processorClass + " and name " + processorName);
            try {
                server.createMBean(processorClass, processorName, null);
            } catch (JMException e) {
                logger.error("Exception creating processor class", e);
            }
        }

        Iterator i = commands.values().iterator();
        while (i.hasNext()) {
            HttpCommandProcessor processor = (HttpCommandProcessor) i.next();
            processor.setMBeanServer(server);
            processor.setDocumentBuilder(builder);
        }

        logger.debug("HttpAdapter server listening on port " + port);
        alive = true;
        Thread serverThread = new Thread(new Runnable() {
            public void run() {
                logger.info("HttpAdapter started on port " + port);

                startDate = new Date();
                requestsCount = 0;

                while (alive) {
                    try {
                        Socket client = null;
                        client = serverSocket.accept();
                        if (!alive) {
                            client.close();
                            break;
                        }
                        requestsCount++;
                        new HttpClient(client).start();
                    } catch (InterruptedIOException e) {
                        continue;
                    } catch (IOException e) {
                        continue;
                    } catch (Exception e) {
                        logger.warn("Exception during request processing", e);
                        continue;
                    } catch (Error e) {
                        logger.error("Error during request processing", e);
                        continue;
                    }
                }
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    logger.warn("Exception closing the server", e);
                }
                serverSocket = null;
                alive = false;
                logger.info("HttpAdapter stopped");
            }
        }, "HttpDaemon");
        serverThread.start();
    } else {
        logger.warn("Start failed, no server target server has been set");
    }
}

From source file:org.muckebox.android.net.DownloadServer.java

@Override
public void run() {
    super.run();//from   w  w  w . j  a  v  a  2s  .co  m

    try {
        d("Starting server on " + mPort);

        mServerSocket = new ServerSocket(mPort, 0, InetAddress.getByName("localhost"));
        mServerSocket.setReuseAddress(true);

        try {
            mReady = true;

            while (!mStopped) {
                Socket socket = null;
                DefaultHttpServerConnection connection = new DefaultHttpServerConnection();

                try {
                    d("Waiting for new connection");

                    socket = mServerSocket.accept();

                    d("Got connection");

                    connection.bind(socket, new BasicHttpParams());
                    mHttpService.handleRequest(connection, mHttpContext);

                    d("Request handling finished");
                } catch (HttpException e) {
                    Log.e(LOG_TAG, "Got HTTP error: " + e);
                } finally {
                    connection.shutdown();

                    if (socket != null)
                        socket.close();

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

        d("Server stopped");
    } catch (IOException e) {
        Log.i(LOG_TAG, "IOException, probably ok");
        e.printStackTrace();
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationTest.java

protected boolean isSocketOpen(String host, Integer port) {
    Socket s = null;
    try {/*from w  w w  .  j a  v a  2s .  c  om*/
        s = new Socket(host, port);
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (Exception e) {
            }
    }
}