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.undertow.server.handlers.HttpTunnelingViaConnectTestCase.java

@Test
public void testConnectViaProxy() throws Exception {

    final HttpHost proxy = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default") + 1, "http");
    final HttpHost target = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"), "http");
    ProxyClient proxyClient = new ProxyClient();
    Socket socket = proxyClient.tunnel(proxy, target, new UsernamePasswordCredentials("a", "b"));
    try {/*from   www. j a  v a  2 s. c om*/
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        boolean found = false;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
            if (line.equals("MyHeader: MyValue")) {
                found = true;
            }
        }
        Assert.assertTrue(found);
    } finally {
        socket.close();
    }
}

From source file:com.l2jfree.loginserver.thread.FloodProtectedListener.java

private boolean isFlooding(Socket connection) {
    if (!Config.FLOOD_PROTECTION)
        return false;

    final String host = connection.getInetAddress().getHostAddress();

    ForeignConnection fConnection = _floodProtection.get(host);
    if (fConnection != null) {
        fConnection.connectionNumber += 1;

        if ((fConnection.connectionNumber > Config.FAST_CONNECTION_LIMIT
                && (System.currentTimeMillis() - fConnection.lastConnection) < Config.NORMAL_CONNECTION_TIME)
                || (System.currentTimeMillis() - fConnection.lastConnection) < Config.FAST_CONNECTION_TIME
                || fConnection.connectionNumber > Config.MAX_CONNECTION_PER_IP) {
            fConnection.connectionNumber -= 1;
            fConnection.lastConnection = System.currentTimeMillis();

            try {
                connection.close();
            } catch (IOException e) {
                _log.warn("", e);
            }//from  w  w  w.j a v a  2  s  .c  o m

            if (!fConnection.isFlooding)
                _log.info("Potential Flood from " + host);

            fConnection.isFlooding = true;
            return true;
        } else if (fConnection.isFlooding) //if connection was flooding server but now passed the check
        {
            fConnection.isFlooding = false;

            _log.info(host + " is not considered as flooding anymore.");
        }

        fConnection.lastConnection = System.currentTimeMillis();
    } else {
        _floodProtection.put(host, new ForeignConnection());
    }

    return false;
}

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

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors./*from  ww  w  . ja va 2s  . com*/
 */
@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 ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(new MockEvent(TEST_MESSAGE));
        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());

    // Ensure test message was written to file
    Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE));
}

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private void requestActiveChecks() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Requesting a list of active checks from the server.");
    }/*from   www. j a va  2 s .  com*/

    Socket socket = new Socket(serverAddress, serverPort);
    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    JSONObject request = new JSONObject();
    request.put("request", "active checks");
    request.put("host", hostName);

    byte[] buffer = getRequest(request);

    output.write(buffer);
    output.flush();

    buffer = new byte[10240];
    int read = 0;
    while ((read = input.read(buffer, 0, 10240)) != -1) {
        baos.write(buffer, 0, read);
    }

    socket.close();

    JSONObject response = getResponse(baos.toByteArray());
    if (response.getString("response").equals("success")) {
        refreshFromActiveChecksResponse(response);

    } else {
        log.warn("Server reported a failure when requesting active checks:" + response.getString("info"));
    }

    lastRefresh = System.currentTimeMillis() / 1000;
}

From source file:disko.flow.analyzers.socket.SocketTransmitter.java

public void writeMessage(Message message) {
    log.debug("Establishing connection to " + host + ":" + port);
    while (true) {
        Socket socket = null;
        ObjectOutputStream out = null;
        try {//from   w ww  .j a v  a2s  .c  om
            socket = new Socket(host, port);
            out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(message);
            out.flush();
            log.debug("Sent " + message);
            return;
        } catch (UnknownHostException e) {
            log.error("Error connecting to " + host + ":" + port, e);
        } catch (IOException e) {
            log.error("Error sending to " + host + ":" + port + " message " + message.getData(), e);
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (Throwable ignored) {
                    log.error("While closing transmitter output.", ignored);
                }
            if (socket != null)
                try {
                    socket.close();
                } catch (Throwable ignored) {
                    log.error("While closing transmitter socket.", ignored);

                }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
            break;
        }
    }
}

From source file:Server.java

/**
 * This is the method that Listener objects call when they accept a
 * connection from a client. It either creates a Connection object for the
 * connection and adds it to the list of current connections, or, if the
 * limit on connections has been reached, it closes the connection.
 *//*from w  w w .ja va 2s. c  o m*/
protected synchronized void addConnection(Socket s, Service service) {
    // If the connection limit has been reached
    if (connections.size() >= maxConnections) {
        try {
            // Then tell the client it is being rejected.
            PrintWriter out = new PrintWriter(s.getOutputStream());
            out.print("Connection refused; " + "the server is busy; please try again later.\n");
            out.flush();
            // And close the connection to the rejected client.
            s.close();
            // And log it, of course
            log("Connection refused to " + s.getInetAddress().getHostAddress() + ":" + s.getPort()
                    + ": max connections reached.");
        } catch (IOException e) {
            log(e);
        }
    } else { // Otherwise, if the limit has not been reached
        // Create a Connection thread to handle this connection
        Connection c = new Connection(s, service);
        // Add it to the list of current connections
        connections.add(c);
        // Log this new connection
        log("Connected to " + s.getInetAddress().getHostAddress() + ":" + s.getPort() + " on port "
                + s.getLocalPort() + " for service " + service.getClass().getName());
        // And start the Connection thread to provide the service
        c.start();
    }
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) {
        @Override/*from ww w  .  jav a2s  .  c  om*/
        public String loadInBackground() {
            StringBuffer instr = new StringBuffer();
            try {
                Socket connection = new Socket(ipAddr, port);
                BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
                OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
                osw.write(formatJSON(command.toUpperCase()));
                osw.write(13);
                osw.flush();
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
                int c;
                while ((c = isr.read()) != 13)
                    instr.append((char) c);
                isr.close();
                bis.close();
                osw.close();
                bos.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instr.toString();
        }
    };
    return loader;
}

From source file:com.webkey.Ipc.java

public void comBinAuth(String turl, String postData) {
    readAuthKey();/*from  w  w w.  j a v a2s . co m*/
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        port = prefs.getString("port", "80");
        Socket s = new Socket("127.0.0.1", Integer.parseInt(port));

        //outgoing stream redirect to socket
        DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
        byte[] utf = postData.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n"
                + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n");
        dataOutputStream.write(utf, 0, utf.length);
        dataOutputStream.flush();
        dataOutputStream.close();
        s.close();
    } catch (IOException e1) {
        //e1.printStackTrace();      
    }
    /*
    //         Log.d(TAG,"post data");
    String target = "http://127.0.0.1:"+port+"/"+authKey+turl;
    //Log.d(TAG,target);
    URL url = new URL(target);
    URLConnection conn = url.openConnection();
    // Set connection parameters.
    conn.setDoInput (true);
    conn.setDoOutput (true);
    conn.setUseCaches (false);
    //Make server believe we are form data...
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    DataOutputStream out = new DataOutputStream (conn.getOutputStream ());
    // Write out the bytes of the content string to the stream.
    out.writeBytes(postData);
    out.flush ();
    out.close ();
    // Read response
    BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ()));
    String temp;
    String response = null;
    while ((temp = in.readLine()) != null){
    response += temp + "\n";
    }
    temp = null;
    in.close ();
    System.out.println("Server response:\n'" + response + "'");
    }catch(Exception e){
    Log.d(TAG,e.toString());
    }
            
    */
}

From source file:com.webkey.Ipc.java

public void sendMessage(String message) {
    readAuthKey();/*ww  w.  j  a va 2s .  co  m*/
    try {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        port = prefs.getString("port", "80");
        Socket s = new Socket("127.0.0.1", Integer.parseInt(port));

        //outgoing stream redirect to socket
        DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
        byte[] utf = message.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + "phonewritechatmessage HTTP/1.1\r\n"
                + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: "
                + Integer.toString(utf.length) + "\r\n\r\n");
        dataOutputStream.write(utf, 0, utf.length);
        dataOutputStream.flush();
        dataOutputStream.close();
        s.close();
    } catch (IOException e1) {
        //e1.printStackTrace();      
    }

}

From source file:com.sshtools.j2ssh.forwarding.ForwardingListener.java

/**
 *
 *///w ww. j ava2  s .c om
public void run() {
    try {
        log.info("Starting forwarding listener thread for '" + name + "'");

        //
        //            ServerSocket server = new ServerSocket(getPortToBind(), 50, InetAddress.getByName(getAddressToBind()));
        //server = new ServerSocket(getPortToBind(), 50, InetAddress.getByName(getAddressToBind()));
        Socket socket;

        while (state.getValue() == StartStopState.STARTED) {
            listening = true;

            socket = server.accept();

            if ((state.getValue() == StartStopState.STOPPED) || (socket == null)) {
                break;
            }

            log.info("Connection accepted, creating forwarding channel");

            try {
                ForwardingSocketChannel channel = createChannel(hostToConnect, portToConnect, socket);

                channel.bindSocket(socket);

                if (connection.openChannel(channel)) {
                    log.info("Forwarding channel for '" + name + "' is open");
                } else {
                    log.warn("Failed to open forwarding chanel " + name);
                    socket.close();
                }
            } catch (Exception ex) {
                log.warn("Failed to open forwarding chanel " + name, ex);

                try {
                    socket.close();
                } catch (IOException ioe) {
                }
            }
        }
    } catch (IOException ioe) {
        /* only warn if the forwarding has not been stopped */
        if (state.getValue() == StartStopState.STARTED) {
            log.warn("Local forwarding listener to " + hostToConnect + ":" + String.valueOf(portToConnect)
                    + " has failed", ioe);
        }
    } finally {
        stop();
    }
}