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:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * @param key/*from  www .  jav a2s  .  co m*/
 * @param value
 * @throws IOException
 */
private void send(final String key, final String value) throws IOException {

    final long start = System.currentTimeMillis();

    final StringBuilder message = new StringBuilder(head);
    message.append(encodeBase64(key));
    message.append(middle);
    message.append(encodeBase64(value == null ? "" : value));
    message.append(tail);

    logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value));
    logger.trace(bundle.getString("zabbix-sender-detailed-message", message));

    Socket socket = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(socket.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = socket.getInputStream();
        final int read = in.read(response);

        final String resp = new String(response);
        logger.debug(bundle.getString("zabbix-sender-received-response", resp));
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp));
        }

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

    final long elapsed = System.currentTimeMillis() - start;
    logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed));
}

From source file:haxball.networking.ConnectionHandler.java

public ConnectionHandler(@NonNull Socket socket, @NonNull Dimension fieldSize, @NonNull Goal goals[], byte id) {
    this.socket = socket;
    this.fieldSize = fieldSize;
    this.id = id;

    try {//  www.  j  ava 2s. c  o  m
        in = socket.getInputStream();
        out = socket.getOutputStream();

        // send dimension size
        out.write(serializeDimension(getFieldSize()));
        out.flush();

        out.write(id);

        out.write(goals.length);
        for (Goal g : goals) {
            out.write(serializeGoal(g));
        }

        // read name from client
        byte b[] = new byte[in.read()];
        if (in.read(b) != b.length) {
            throw new IOException();
        }
        name = new String(b, StandardCharsets.UTF_8);
        System.out.println("Connected client " + getSocket() + " as name " + name);

        // create player
        player = new Player(getId(), getName(), fieldSize);
        player.position = new Vector2D(100, 100);
    } catch (Exception ioe) {
        ioe.printStackTrace();
        try {
            socket.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.supernovapps.audio.jstreamsourcer.Icecast.java

public boolean start(Socket sock) {
    try {/*from www  .  j  a  v  a  2  s .c o  m*/
        this.sock = sock;
        sock.connect(new InetSocketAddress(host, port), timeout);
        sock.setSendBufferSize(64 * 1024);
        out = sock.getOutputStream();

        PrintWriter output = new PrintWriter(out);
        output.println("SOURCE " + path + " HTTP/1.0");

        writeAuthentication(output);
        writeHeaders(output);

        output.println("");
        output.flush();

        InputStreamReader isr = new InputStreamReader(sock.getInputStream());
        BufferedReader in = new BufferedReader(isr);
        String line = in.readLine();

        if (line == null || !line.contains("HTTP") || !line.contains("OK")) {
            if (listener != null) {
                listener.onError("Connection / Authentification error");
            }
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();

        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if (listener != null) {
            listener.onError("Connection / Authentification error");
        }

        return false;
    }
    started = true;

    if (listener != null) {
        listener.onConnected();
    }

    return true;
}

From source file:WebServer.java

/**
 * WebServer constructor./*from w  ww .  ja  va2s  .  c om*/
 */
protected void start() {
    ServerSocket s;

    System.out.println("Webserver starting up on port 80");
    System.out.println("(press ctrl-c to exit)");
    try {
        // create the main server socket
        s = new ServerSocket(80);
    } catch (Exception e) {
        System.out.println("Error: " + e);
        return;
    }

    System.out.println("Waiting for connection");
    for (;;) {
        try {
            // wait for a connection
            Socket remote = s.accept();
            // remote is now the connected socket
            System.out.println("Connection, sending data.");
            BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
            PrintWriter out = new PrintWriter(remote.getOutputStream());

            // read the data sent. We basically ignore it,
            // stop reading once a blank line is hit. This
            // blank line signals the end of the client HTTP
            // headers.
            String str = ".";
            while (!str.equals(""))
                str = in.readLine();

            // Send the response
            // Send the headers
            out.println("HTTP/1.0 200 OK");
            out.println("Content-Type: text/html");
            out.println("Server: Bot");
            // this blank line signals the end of the headers
            out.println("");
            // Send the HTML page
            out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
            out.flush();
            remote.close();
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

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

private void unLockSocket() throws IOException {
    // Need to create a connection to unlock the accept();
    Socket s;
    InetAddress ladr = inet;/*  ww  w . java  2s  .c  o m*/

    if (port == 0) {
        return;
    }
    if (ladr == null || "0.0.0.0".equals(ladr.getHostAddress())) {
        ladr = InetAddress.getLocalHost();
    }
    s = new Socket(ladr, port);
    // setting soLinger to a small value will help shutdown the
    // connection quicker
    s.setSoLinger(true, 0);

    s.close();
}

From source file:com.adito.jdbc.hsqldb.EmbeddedHSQLDBServer.java

void waitForServer() {
    if (!testedConnection && serverMode) {
        Socket s = null;
        String addr = server.getAddress().equals("0.0.0.0") ? "127.0.0.1" : server.getAddress();
        if (log.isInfoEnabled())
            log.info("Waiting for HSQLDB to start accepting connections on " + addr + ":" + server.getPort());
        for (int i = 0; i < 30; i++) {
            try {
                s = new Socket(addr, server.getPort());
                break;
            } catch (IOException ioe) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }/*from  w ww  .  j  a  v a  2s. c om*/
            }
        }
        if (s == null) {
            throw new IllegalStateException("The HSQLDB server is not accepting connections after 30 seconds.");
        } else {
            testedConnection = true;
            if (log.isInfoEnabled())
                log.info("HSQLDB is now accepting connections.");
            try {
                s.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:net.jotel.ws.client.WebSocketClient.java

private void tryConnect() throws IOException {
    log.info("Trying to connect");

    socket = createSocket();//from  www  . j a  v a2s.co m

    try {
        outputStream = socket.getOutputStream();
        inputStream = socket.getInputStream();

        handshake();
    } catch (IOException ex) {
        Socket s = socket;
        socket = null;
        outputStream = null;
        inputStream = null;

        try {
            s.close();
        } catch (Exception e) {
            // ignore
        }
        throw ex;
    }

    readerThread = new WebSocketReaderThread(this);
    readerThread.start();

    keepAliveThread = new WebSocketKeepAliveThread(this);
    keepAliveThread.start();
}

From source file:com.barchart.udt.AppServer.java

private static void copyFile(final Socket sock) {
    log.info("Inside copy file ");
    final Runnable runner = new Runnable() {
        public void run() {
            InputStream is = null;
            OutputStream os = null;
            try {
                is = sock.getInputStream();
                final byte[] bytes = new byte[1024];
                final int bytesRead = is.read(bytes);
                final String str = new String(bytes);
                if (str.startsWith("GET ")) {
                    int nameIndex = 0;
                    for (final byte b : bytes) {
                        if (b == '\n') {
                            break;
                        }//from ww w  .ja v  a  2  s.c  o m
                        nameIndex++;
                    }
                    // Eat the \n.
                    nameIndex++;
                    final String fileName = new String(bytes, 4, nameIndex).trim();
                    log.info("File name: " + fileName);
                    final File f = new File(fileName);
                    final FileInputStream fis = new FileInputStream(f);
                    os = sock.getOutputStream();

                    copy(fis, os, f.length());
                    os.close();
                    return;
                }
                int nameIndex = 0;
                int lengthIndex = 0;
                boolean foundFirst = false;
                //boolean foundSecond = false;
                for (final byte b : bytes) {
                    if (!foundFirst) {
                        nameIndex++;
                    }
                    lengthIndex++;
                    if (b == '\n') {
                        if (foundFirst) {
                            break;
                        }
                        foundFirst = true;
                    }
                }
                if (nameIndex < 2) {
                    // First bytes was a LF?
                    sock.close();
                    return;
                }
                String dataString = new String(bytes);
                int fileLengthIndex = dataString.indexOf("\n", nameIndex + 1);
                final String fileName = new String(bytes, 0, nameIndex).trim();
                final String lengthString = dataString.substring(nameIndex, fileLengthIndex);
                log.info("lengthString " + lengthString);
                final long length = Long.parseLong(lengthString);
                final File file = new File(fileName);
                os = new FileOutputStream(file);
                final int len = bytesRead - lengthIndex;
                if (len > 0) {
                    os.write(bytes, lengthIndex, len);
                }
                start = System.currentTimeMillis();
                copy(is, os, length);
            } catch (final IOException e) {
                log.info("Exception reading file...", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(sock);
            }
        }
    };
    log.info("Executing copy...");
    readPool.execute(runner);
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * Retrieves all active checks configured in the server.
 * /*  www  .j a  v  a  2s  . co m*/
 * @param hostname
 * @return   List<ActiveCheck>
 * @throws IOException
 */
public List<ActiveCheck> getActiveChecks(String hostname) throws IOException {

    List<ActiveCheck> list = new ArrayList<ActiveCheck>();

    Socket socket = null;
    OutputStream out = null;
    BufferedReader brin = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

        out = socket.getOutputStream();
        brin = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // send request to Zabbix server and wait for the list of items to be returned
        out.write(createGetActiveChecksRequest(hostname));

        while (!socket.isClosed()) {
            String line = brin.readLine();

            if (line == null)
                break;

            // all active checks received
            if (line.startsWith(ZBX_EOF))
                break;

            list.add(parseActiveCheck(hostname, line));
        }

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

    return list;
}

From source file:info.sugoiapps.xoserver.XOverServer.java

/**
 * The main background task./* w  w w  .j a  v a 2  s.  co  m*/
 * Accept connection from the server socket and read incoming messages.
 * Pass messages to mouse event handler.
 */
private void listen() {
    Socket socket = null;
    InputStream in = null;
    publish(CONNECTED_MESSAGE + PORT);
    System.out.println("about to enter server loop");
    while (!Thread.interrupted()) { //!Thread.interrupted()
        try {
            socket = server.accept(); // stop is clicked, this is still waiting for incoming connections, 
                                      // therefore once the server is closed, it will produce an error
                                      //socket.setKeepAlive(false);
            System.out.println("started accepting from socket");
        } catch (IOException ex) {
            serverClosedMessage(ex);
            break;
        }

        try {
            in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (isCancelled()) {
                    in.close();
                    isr.close();
                    br.close();
                    socket.close();
                    break;
                }
                if (!addressReceived && isValidAddress(line)) {
                    System.out.println("address check entered");
                    addressReceived = true;
                    hostAddress = line;
                    startFileClient();
                } else {
                    imitateMouse(line);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            serverClosedMessage(ex);
        }
    }
}