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:io.s4.client.Handshake.java

public ClientConnection execute(Socket s) {
    byte[] v;/*  w ww.  j a v  a  2 s  . com*/

    try {
        ClientConnection conn = null;

        ByteArrayIOChannel io = new ByteArrayIOChannel(s);

        v = io.recv();

        if (v == null || v.length == 0) {
            // no information => client initialization
            clientInit(io);

        } else {
            // some data => client connect
            conn = clientConnect(v, io, s);
        }

        if (conn == null)
            s.close();

        return conn;

    } catch (IOException e) {
        logger.error("exception during handshake", e);
        try {
            s.close();
            return null;

        } catch (IOException ee) {
            throw new RuntimeException("failed to close socket after failed handshake", ee);
        }
    }
}

From source file:com.brienwheeler.lib.io.ReconnectingSocket.java

private void tryToWrite(byte data[]) {
    Socket writeSocket = socket.get();
    if (writeSocket == null)
        return;// w  w  w .  j  a v a  2s . c  o m

    try {
        OutputStream outputStream = writeSocket.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    } catch (IOException e) {
        if (socket.compareAndSet(writeSocket, null)) {
            log.error("error writing to " + hostname, e);
            onDisconnected();
            startConnectThread(reconnectPeriodicity);
            try {
                writeSocket.close();
            } catch (IOException e1) {
                // silent
            }
        }
    }
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

private void query(int port, String key, byte[] expected) throws IOException {
    final Socket socket = new Socket(InetAddress.getLocalHost(), port);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write(key);//from w w w  .j  a v a 2  s  .  c  o  m
    out.write('\n');
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);
    socket.close();
    System.out.println(new String(buffer));
    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);
    assertEquals((byte) 0x01, buffer[4]);
    byte[] actual = Arrays.copyOfRange(buffer, 13, 13 + expected.length);
    assertArrayEquals(expected, actual);
    //        assertTrue(Arrays.equals(expected, actual));
}

From source file:com.inmobi.messaging.util.GraphiteStatsEmitter.java

protected void writeStats() {
    if (null != statsExposers) {
        synchronized (statsExposers) {
            final StringBuilder lines = new StringBuilder();
            long timestamp = System.currentTimeMillis() / 1000;
            for (StatsExposer exposer : statsExposers) {
                Map<String, Number> stats = exposer.getStats();
                Map<String, String> context = exposer.getContexts();
                String topic = context.get(TopicStatsExposer.TOPIC_CONTEXT_NAME);
                /**//from w ww .j ava 2 s.c  o  m
                 * Publisher will be having topic set as category in the statsexposer,
                 * but for consumers topic is set as topicName for the statsexposer.
                 */
                if (null == topic) {
                    topic = context.get(MessageConsumerMetricsConstants.TOPIC_CONTEXT);
                }
                for (Map.Entry<String, Number> entry : stats.entrySet()) {
                    lines.append(metricPrefix).append(topic).append(METRIC_SEPARATOR).append(entry.getKey());
                    lines.append(FIELD_SEPARATOR);
                    lines.append(entry.getValue().longValue());
                    lines.append(FIELD_SEPARATOR);
                    lines.append(timestamp);
                    lines.append(NEW_LINE);
                }
            }

            Socket graphiteSocket = null;
            OutputStream stream = null;
            try {
                graphiteSocket = new Socket(graphiteHost, graphitePort);
                stream = graphiteSocket.getOutputStream();
                stream.write(lines.toString().getBytes(Charset.forName("UTF-8")));
            } catch (IOException ex) {
                LOG.error("Failed to write the stats", ex);
            } finally {
                if (null != graphiteSocket && !graphiteSocket.isClosed()) {
                    try {
                        graphiteSocket.close();
                    } catch (IOException ex) {
                        LOG.warn("failure in closing the connection to graphite server", ex);
                    }
                }
                if (null != stream) {
                    try {
                        stream.close();
                    } catch (IOException ex) {
                        LOG.warn("failure in closing the input stream", ex);
                    }
                }
            }
        }
    }
}

From source file:com.predic8.membrane.core.transport.http.HttpEndpointListener.java

@Override
public void run() {
    while (!closed) {
        try {/*w  w  w.  j  a  v a2  s .  c  o m*/
            Socket socket = serverSocket.accept();
            openSockets.put(socket, Boolean.TRUE);
            try {
                transport.getExecutorService().execute(new HttpServerHandler(socket, this));
            } catch (RejectedExecutionException e) {
                openSockets.remove(socket);
                log.error(
                        "HttpServerHandler execution rejected. Might be due to a proxies.xml hot deployment in progress or a low"
                                + " value for <transport maxThreadPoolSize=\"...\">.");
                socket.close();
            }
        } catch (SocketException e) {
            String message = e.getMessage();
            if (message != null && (message.endsWith("socket closed") || message.endsWith("Socket closed"))) {
                log.debug("socket closed.");
                break;
            } else
                log.error(e);
        } catch (NullPointerException e) {
            // Ignore this. serverSocket variable is set null during a loop in the process of closing server socket.
        } catch (Exception e) {
            log.error(e);
        }
    }
}

From source file:com.dumbster.smtp.SimpleSmtpServer.java

/**
 * Main loop of the SMTP server./*from w w w .ja va  2 s .  c o  m*/
 */
public void run() {
    stopped = false;
    try {
        try {
            serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5
            // seconds
        } finally {
            synchronized (this) {
                // Notify when server socket has been created
                notifyAll();
            }
        }

        // Server: loop until stopped
        while (!isStopped()) {
            // Start server socket and listen for client connections
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (Exception e) {
                if (socket != null) {
                    socket.close();
                }
                continue; // Non-blocking socket timeout occurred: try
                          // accept() again
            }

            // Get the input and output streams
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());

            synchronized (this) {
                /*
                 * We synchronize over the handle method and the list update
                 * because the client call completes inside the handle
                 * method and we have to prevent the client from reading the
                 * list until we've updated it. For higher concurrency, we
                 * could just change handle to return void and update the
                 * list inside the method to limit the duration that we hold
                 * the lock.
                 */
                List<SmtpMessage> msgs = handleTransaction(out, input);
                saveMessagesInElasticSearch(msgs);
            }
            socket.close();
        }
    } catch (Exception e) {
        logger.error("Smtp Server could not be started", e);
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:client.communication.SocketClient.java

/**
 * Envia a mensagem para o servidor e retorna a resposta
 * /* w w w. j ava  2  s . co  m*/
 * @param message
 * @return 
 */
public String sendMessage(String message) {
    Socket socket = null;

    PrintStream stream = null;

    try {
        socket = new Socket(serverAddress, serverPort);

        stream = new PrintStream(socket.getOutputStream());

        // Envia requisiao
        stream.println(message);

        // L resposta
        socket.getInputStream().read(response);
    } catch (IOException e) {
        System.out.println("Problem connecting server!");
    } finally {
        try {
            // Fecha stream
            if (stream != null)
                stream.close();

            if (socket != null)
                socket.close();
        } catch (IOException e) {
            System.err.println("Problem closing socket: " + e.getMessage());
        }
    }

    // Decodifica resposta em base 64
    String _reply = new String(Base64.decodeBase64(response));

    // Remove o espao nas extremidades da string de resposta
    return _reply.trim();
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

public void doDispose() {
    for (Socket connectedSocket : connectedSockets.values()) {
        if (null != connectedSocket && !connectedSocket.isClosed()) {
            try {
                connectedSocket.close();
                connectedSockets.values().remove(connectedSocket);
                connectedSocket = null;//from  ww  w . j a  v a2 s. c o m
            } catch (IOException e) {
                logger.debug("ConnectedSocked close raised exception. Reason: " + e.getMessage());
            }
        }
    }
}

From source file:net.pms.network.HTTPServer.java

@Override
public void run() {
    logger.info("Starting DLNA Server on host {} and port {}...", hostname, port);

    while (!stop) {
        try {//  w  w w  . ja  v a  2s . co  m
            Socket socket = serverSocket.accept();
            InetAddress inetAddress = socket.getInetAddress();
            String ip = inetAddress.getHostAddress();
            // basic IP filter: solntcev at gmail dot com
            boolean ignore = false;

            if (configuration.getIpFiltering().allowed(inetAddress)) {
                logger.trace("Receiving a request from: " + ip);
            } else {
                ignore = true;
                socket.close();
                logger.trace("Ignoring request from: " + ip);
            }

            if (!ignore) {
                RequestHandler request = new RequestHandler(socket);
                Thread thread = new Thread(request, "Request Handler");
                thread.start();
            }
        } catch (ClosedByInterruptException e) {
            stop = true;
        } catch (IOException e) {
            logger.debug("Caught exception", e);
        } finally {
            try {
                if (stop && serverSocket != null) {
                    serverSocket.close();
                }

                if (stop && serverSocketChannel != null) {
                    serverSocketChannel.close();
                }
            } catch (IOException e) {
                logger.debug("Caught exception", e);
            }
        }
    }
}

From source file:ch.algotrader.adapter.ib.IBSession.java

private void waitAndConnect() {

    while (!isTerminated()) {

        Socket socket = new Socket();
        try {//from   ww  w .j ava  2  s  .co m
            socket.connect(new InetSocketAddress(this.host, this.port), 5000);
            eConnect(socket, this.clientId);
            return;
        } catch (ConnectException e) {
            // do nothing, gateway is down
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("please start IB Gateway / TWS on port: {}", this.port);
            }
        } catch (IOException e) {
            LOGGER.error("connection error", e);
        }
        try {
            socket.close();
        } catch (IOException ignore) {
        }

        sleep();
    }

}