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 robustness./*from   w w w. j a  v a2  s . c om*/
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingOpen() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx(foo]\n");
    out.flush();

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

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

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

From source file:pl.edu.agh.BackgroundServiceConnection.java

/**
 * Compares sent hash to the one in database
 *//*  www. j  av a2  s  .c om*/
public void run() {
    while (true) {
        try {
            LOGGER.info("Accepting connections on port: " + serverPort);
            Socket client = serverSocket.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String message = in.readLine();
            DataOutputStream out = new DataOutputStream(client.getOutputStream());

            LOGGER.info("Daemon message: " + message);

            String[] data = message.trim().split("\\|");
            try {
                Service service = serviceDAO.getById(Integer.parseInt(data[1]));
                if (!data[0].equalsIgnoreCase(service.getPassword()))
                    throw new IllegalArgumentException("Daemon password: " + data[0]
                            + " does not match server password: " + service.getPassword());
                out.writeBytes("OK\r\n");
            } catch (Exception e) {
                LOGGER.error("Could not find server: " + message.trim(), e);
                out.writeBytes("ERROR\r\n");
            }

            in.close();
            out.close();
            client.close();

        } catch (Exception e) {
            LOGGER.error("Error connecting with server: " + e.getMessage());
        }
    }
}

From source file:de.th.wildau.dsc.sne.webserver.WebServer.java

/**
 * Web server / main constructor.//from ww w  .j a  v  a 2  s  .  c o  m
 * 
 * @param startArguments
 */
public WebServer(String[] startArguments) {

    loadConfiguration(startArguments);
    Log.debug(Configuration.getInstance().toString());

    Log.debug("Information about the OS: " + System.getProperty("os.name") + " - "
            + System.getProperty("os.version") + " - " + System.getProperty("os.arch"));

    if (Configuration.getConfig().getProxyHost() != null) {
        Log.debug("setup proxy configuration");
        System.setProperty("http.proxyHost", Configuration.getConfig().getProxyHost());
        System.setProperty("http.proxyPort", String.valueOf(Configuration.getConfig().getProxyPort()));
    }

    Log.debug("find supported scripting languages");
    supportedScriptLanguages = Collections.unmodifiableList(ScriptExecutor.getSupportedScriptLanguages());
    Log.debug("Supported Script Languages " + Arrays.toString(supportedScriptLanguages.toArray()));

    Log.info("instantiating web server");
    try {
        ServerSocket server = new ServerSocket(Configuration.getConfig().getServerPort());
        Log.debug("bound port " + Configuration.getConfig().getServerPort());

        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = (2 * corePoolSize) + 1;
        Log.debug("core/max pool size: " + corePoolSize + "/" + maxPoolSize);
        LinkedBlockingQueue<Runnable> workerQueue = new LinkedBlockingQueue<Runnable>();
        long keepAliveTime = 30;
        /*
         * keepAliveTime - If the pool currently has more than corePoolSize
         * threads, excess threads will be terminated if they have been idle
         * for more than the keepAliveTime.
         */

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, workerQueue);
        threadPool.prestartAllCoreThreads();

        Socket socket = null;
        while (true) {

            try {
                socket = server.accept();
                Log.info(socket.getInetAddress().getHostName() + " client request");
                threadPool.execute(new HttpHandler(socket));
                Log.debug("current threads: " + threadPool.getActiveCount());
            } catch (final IOException ex) {
                Log.error("Connection failed!", ex);
            } catch (final RejectedExecutionException ex) {
                // XXX [sne] RejectedExecutionException
                // http://stackoverflow.com/questions/1519725/why-does-executors-newcachedthreadpool-throw-java-util-concurrent-rejectedexecut
                // http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml
                // http://stackoverflow.com/questions/2001086/how-to-make-threadpoolexecutors-submit-method-block-if-it-is-saturated
                Log.error("RejectedExecutionException", ex);
                socket.close();
            } catch (final Exception ex) {
                Log.fatal("Unknown error!", ex);
            }
        }
    } catch (final IOException ex) {
        Log.fatal("Can not start the server!", ex);
        System.err.println("Can not start the server! " + ex.getMessage());
    } catch (final Exception ex) {
        Log.fatal("Unknown error!", ex);
    }
}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Opens a client socket to the specified port. If this is successful
 * then the port is returned, otherwise it is closed and null is
 * returned./*from   w w w. j  av a  2 s .co m*/
 * 
 * @param appId
 *            The application ID.
 * @param port
 *            The port number to connect to.
 * @return The client socket or null if no connection to
 *         the server was possible or the server is not the same
 *         application.
 */
private Socket openClientSocket(String appId, int port) {
    try {
        Socket socket = new Socket(InetAddress.getByName(null), port);
        try {
            // Open communication channels
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

            // Read the appId from the server. Use a one second timeout for
            // this just in case some unresponsive application listens on
            // this port.
            socket.setSoTimeout(1000);
            String serverAppId = in.readLine();
            socket.setSoTimeout(0);

            // Abort if server app ID doesn't match (Or there was none at
            // all)
            if (serverAppId == null || !serverAppId.equals(appId)) {
                socket.close();
                socket = null;
            }

            return socket;
        } catch (IOException e) {
            socket.close();
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors./* w  w  w.  j  a v a  2  s.c  o  m*/
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final LoggingEvent event = new LoggingEvent(TEST_CATEGORY, Logger.getLogger(TEST_CATEGORY), Level.DEBUG,
                TEST_MESSAGE, null);
        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(event);
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    for (AppenderConfig appender : testProject.getAppenders()) {
        final String logFilePath = FileHelper.pathCat(CLIENT_ROOT_DIR, testProject.getName(),
                appender.getAppenderParam("file").getValue());
        final String contents = readTextFile(logFilePath);
        Assert.assertTrue(contents.contains(TEST_MESSAGE));
    }
}

From source file:com.meh.CopyProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*from   w  ww  . j  a v a 2  s.c  o m*/
    }
    Log.d(tag, "processing");
    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

    Log.d(tag, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    try {
        byte[] buffer = new byte[1024 * 50];

        int readBytes;
        while (isRunning && (readBytes = data.read(buffer, 0, buffer.length)) != -1) {
            client.getOutputStream().write(buffer, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Register state variable events notification for a device service
 * @param service the service to register with
 * @param handler the registrant object//from   w w  w . j  a  v  a2 s  .  c  o m
 * @param subscriptionDuration subscription time in seconds, -1 for infinite time
 * @return an ServiceEventSubscription object instance containing all the required info or null if no subscription done
 * @throws IOException if some IOException error happens during coms with the device
 */
public ServiceEventSubscription registerEvent(UPNPService service, ServiceEventHandler handler,
        int subscriptionDuration) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        if (!inService)
            startServicesEventingThread();
        String duration = Integer.toString(subscriptionDuration);
        if (subscriptionDuration == -1) {
            duration = "infinite";
        }

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            // allready registered let's try to unregister it
            unRegister(service, handler);
        }

        StringBuffer packet = new StringBuffer(64);
        packet.append("SUBSCRIBE ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
        packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                .append("\r\n");
        packet.append("CALLBACK: <http://").append(InetAddress.getLocalHost().getHostAddress()).append(":")
                .append(daemonPort).append("").append(eventingLoc.getFile()).append(">\r\n");
        packet.append("NT: upnp:event\r\n");
        packet.append("Connection: close\r\n");
        packet.append("TIMEOUT: Second-").append(duration).append("\r\n\r\n");

        Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort());
        skt.setSoTimeout(30000); // 30 secs timeout according to the specs
        if (log.isDebugEnabled())
            log.debug(packet);
        OutputStream out = skt.getOutputStream();
        out.write(packet.toString().getBytes());
        out.flush();

        InputStream in = skt.getInputStream();
        StringBuffer data = new StringBuffer();
        int readen = 0;
        byte[] buffer = new byte[256];
        while ((readen = in.read(buffer)) != -1) {
            data.append(new String(buffer, 0, readen));
        }
        in.close();
        out.close();
        skt.close();
        if (log.isDebugEnabled())
            log.debug(data.toString());
        if (data.toString().trim().length() > 0) {
            HttpResponse resp = new HttpResponse(data.toString());

            if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) {
                String sid = resp.getHTTPHeaderField("SID");
                String actualTimeout = resp.getHTTPHeaderField("TIMEOUT");
                int durationTime = 0;
                // actualTimeout = Second-xxx or Second-infinite
                if (!actualTimeout.equalsIgnoreCase("Second-infinite")) {
                    durationTime = Integer.parseInt(actualTimeout.substring(7));
                }
                sub = new Subscription();
                sub.handler = handler;
                sub.sub = new ServiceEventSubscription(service.getServiceType(), service.getServiceId(),
                        service.getEventSubURL(), sid, skt.getInetAddress(), durationTime);
                synchronized (registered) {
                    registered.add(sub);
                }
                return sub.sub;
            }
        }
    }
    return null;

}

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

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

        PrintWriter output = writeAuthentication();

        InputStreamReader isr = new InputStreamReader(sock.getInputStream());
        BufferedReader in = new BufferedReader(isr);
        String line = in.readLine();
        if (line == null || !line.contains("OK")) {
            if (listener != null) {
                listener.onError("Connection / Authentification error");
            }

            return false;
        }

        while (line != null && line.length() > 0) {
            line = in.readLine();
        }

        writeHeaders(output);
    } 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:com.raddle.tools.ClipboardTransferMain.java

private void shutdown() {
    Socket socket = null;
    try {//ww w.  j  a  va2  s . co  m
        tostop = true;
        socket = new Socket("127.0.0.1", Integer.parseInt(portTxt.getText()));
        socket.setSoTimeout(2000);
        ClipCommand cmd = new ClipCommand();
        cmd.setCmdCode(ClipCommand.CMD_SHUTDOWN);
        // ??
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        out.writeObject(cmd);
    } catch (Exception e) {
        updateMessage("??:" + e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Unregisters events notifications from a service
 * @param service the service that need to be unregistered
 * @param handler the handler that registered for this service
 * @return true if unregistered false otherwise ( the given handler never registred for the given service )
 * @throws IOException if some IOException error happens during coms with the device
 *//*from  www. ja v  a 2s. c o m*/
public boolean unRegister(UPNPService service, ServiceEventHandler handler) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            synchronized (registered) {
                registered.remove(sub);
            }
            if (registered.size() == 0) {
                stopServicesEventingThread();
            }

            StringBuffer packet = new StringBuffer(64);
            packet.append("UNSUBSCRIBE  ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
            packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                    .append("\r\n");
            packet.append("SID: ").append(sub.sub.getSID()).append("\r\n\r\n");
            Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort());
            skt.setSoTimeout(30000); // 30 secs timeout according to the specs
            if (log.isDebugEnabled())
                log.debug(packet);
            OutputStream out = skt.getOutputStream();
            out.write(packet.toString().getBytes());
            out.flush();

            InputStream in = skt.getInputStream();
            StringBuffer data = new StringBuffer();
            int readen = 0;
            byte[] buffer = new byte[256];
            while ((readen = in.read(buffer)) != -1) {
                data.append(new String(buffer, 0, readen));
            }
            in.close();
            out.close();
            skt.close();
            if (log.isDebugEnabled())
                log.debug(data.toString());
            if (data.toString().trim().length() > 0) {
                HttpResponse resp = new HttpResponse(data.toString());
                if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) {
                    return true;
                }
            }
        }
    }
    return false;
}