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.plotsquared.iserver.core.Worker.java

/**
 * Accepts a remote socket,/* w  w  w  .  j  a v  a  2 s.c om*/
 * makes sure its handled and closed down successfully
 * @param remote Socket to accept
 */
public void run(final Socket remote) {
    if (remote != null && !remote.isClosed()) {
        handle(remote);
    }
    if (remote != null && !remote.isClosed()) {
        try {
            remote.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    // MUST BE CALLED LAST
    availableWorkers.add(this);
}

From source file:org.openmrs.module.mirebalais.integration.MirthIT.java

private String listenForResults() throws IOException {

    ServerSocket listener = new ServerSocket(6660); // TODO: store this port in a global property?
    listener.setSoTimeout(20000); // don't wait more than 20 seconds for an incoming connection

    Socket mirthConnection = listener.accept();

    BufferedReader reader = new BufferedReader(new InputStreamReader(mirthConnection.getInputStream()));

    StringBuilder sb = new StringBuilder();
    String line;//from   w ww  .jav a 2s . c  o  m

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    // TODO: need an acknowledgement?

    mirthConnection.close();
    listener.close();

    return sb.toString();
}

From source file:org.apache.solr.client.solrj.impl.BasicHttpSolrServerTest.java

private int findUnusedPort() {
    for (int port = 0; port < 65535; port++) {
        Socket s = new Socket();
        try {//from  ww w  . j  a v a 2  s  .co m
            s.bind(null);
            int availablePort = s.getLocalPort();
            s.close();
            return availablePort;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    throw new RuntimeException("Could not find unused TCP port.");
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServerTest.java

public void testInvalidHandshake() throws IOException, JSONException, InterruptedException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);//from w  w w .  j a  va 2s  . c o  m
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("bar")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertTrue(JSONObject.NULL != error);
    while (!out.checkError()) {
        out.println(buildRequest(0, "makeToast", Lists.newArrayList("baz")));
    }
    client.close();
    // Further connections should fail;
    client = new Socket();
    try {
        client.connect(address);
        fail();
    } catch (IOException e) {
    }
}

From source file:info.varden.irclinqed.dcc.FileReceiveThread.java

@Override
public void run() {
    try {/*from  w  w w  .java2  s .c o m*/
        this.il.keyListenerQueue.add(this);
        this.gfp = new GuiFileProgress(this.packet.il, this);
        this.packet.il.guiQueue.add(this.gfp);
        if (!this.file.getParentFile().exists()) {
            this.file.getParentFile().mkdirs();
        }
        if (!this.file.exists()) {
            this.file.createNewFile();
        }
        Socket s = new Socket(this.host, this.port);
        InputStream i = s.getInputStream();
        this.cos = new CountingOutputStream(new FileOutputStream(this.file));
        byte[] buff = new byte[1024];
        int k = -1;
        while ((k = i.read(buff)) > -1 && !this.cancel) {
            this.cos.write(buff, 0, k);
            s.getOutputStream().write(ByteBuffer.allocate(4).putInt((int) getByteCount()).array());
        }
        s.shutdownInput();
        s.shutdownOutput();
        s.close();
        this.cos.close();
        this.gfp.unload();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sshtools.daemon.SshServer.java

/**
 *
 *
 * @throws IOException//from  ww w  . j a v a  2 s.  com
 */
protected void startCommandSocket() throws IOException {
    try {

        /**
         * A potential problem exists here. What happens if the command
         * server socket is dropped for any reason? This will cause the
         * server to stop.
         */
        commandServerSocket = new ServerSocket(
                ((ServerConfiguration) ConfigurationLoader.getConfiguration(ServerConfiguration.class))
                        .getCommandPort(),
                50, InetAddress.getByName("127.0.0.1"));
        Socket client;

        while ((client = commandServerSocket.accept()) != null) {
            log.info("Command request received");

            // Read and process the command
            processCommand(client.getInputStream().read(), client);
            client.close();

            if (shutdown) {
                break;
            }
        }

        commandServerSocket.close();

    } catch (Exception e) {
        if (!shutdown) {
            log.fatal("The command socket failed", e);
        }
    }

}

From source file:de.kapsi.net.daap.bio.DaapServerBIO.java

/**
 * The run loop/* w w  w  .  j  av a2s .  c o  m*/
 */
public void run() {

    threadNo = 0;
    running = true;

    try {

        while (running) {
            Socket socket = ssocket.accept();

            try {

                if (running && !accept(socket)) {

                    socket.close();
                }

            } catch (IOException err) {
                LOG.error(err);
                try {
                    socket.close();
                } catch (IOException ignored) {
                }
            }

            Thread.sleep(100);
        }

    } catch (InterruptedException err) {
        LOG.error(err);
        //   throw new RuntimeException(err);

    } catch (SocketException err) {
        if (running) {
            LOG.error(err);
        }
        //  throw new RuntimeException(err);

    } catch (IOException err) {
        LOG.error(err);
        //  throw new RuntimeException(err);

    } finally {
        stop();
    }
}

From source file:com.irccloud.android.GingerbreadImageProxy.java

public void run() {
    while (isRunning) {
        try {/*from   w w  w.  j  ava 2  s .co m*/
            Socket client = socket.accept();
            if (client == null) {
                continue;
            }
            HttpRequest request = readRequest(client);
            if (isRunning)
                processRequest(request, client);
            client.close();
        } catch (SocketTimeoutException e) {
            // Do nothing
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to client", e);
        }
    }
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testWriteClose() throws IOException {
    // Create a task to be executed following the acceptance of a new connection to the server socketChannel.
    // This task is the application entry point.
    // This task will write out the message "Hello and Goodbye" and then close the connection.
    ISocketChannelHandler socketChannelHandler = (nbContext, socket) -> WriteMessageTask.Builder.builder()
            .withByteBuffer(ByteBuffer.allocate(2048)).build()
            .writeMessage("Hello and Goodbye\n".getBytes(StandardCharsets.UTF_8), nbContext, socket,
                    () -> IOUtils.closeQuietly(socket), (e) -> LOG.error("Write failed", e));
    // create the server
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(//from ww  w .j av  a  2s.  c o  m
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            // Here we configure the provider for the listening socketChannel.  In this case,
            // a TCP server socketChannel will be created using the default TcpAcceptedConnectionHandler
            // to handle incoming connections and pass them off to the socketChannelHandler
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    // supply the application entry point
                    .withConnectedSocketTask(socketChannelHandler).build())
            .build();
    try {
        simpleNbServer.start();
        Socket socket = new Socket("localhost", 1111);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        String message = reader.readLine();
        System.out.println("Received message '" + message + "' from the server");
        Assert.assertEquals("Hello and Goodbye", message);
        socket.close();
    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

protected String sendMessage(String message) throws IOException {
    LOG.info("sending message '" + message + "'");
    Socket socket = new Socket("localhost", 1111);
    OutputStream out = socket.getOutputStream();
    InputStream in = socket.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
    out.write((message + '\n').getBytes(StandardCharsets.UTF_8));
    String response = reader.readLine();
    LOG.info("recieved response '" + response + "'");
    socket.close();
    return response;
}