Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

In this page you can find the example usage for java.net Socket getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java

@Override
public Socket wrapAcceptedSocket(Socket socket) throws IOException {
    InputStream ins = socket.getInputStream();

    byte[] buffer = new byte[0xFF];
    int position = 0;
    SSLCapabilities capabilities = null;

    // Read the header of TLS record
    while (position < SSLExplorer.RECORD_HEADER_SIZE) {
        int count = SSLExplorer.RECORD_HEADER_SIZE - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }//from  ww w.  j  a va 2 s.  c  o  m
        position += n;
    }

    // Get the required size to explore the SSL capabilities
    int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position);
    if (buffer.length < recordLength) {
        buffer = Arrays.copyOf(buffer, recordLength);
    }

    while (position < recordLength) {
        int count = recordLength - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }
        position += n;
    }

    capabilities = SSLExplorer.explore(buffer, 0, recordLength);

    SSLContext sslContext = null;

    if (capabilities != null) {
        List<SNIServerName> serverNames = capabilities.getServerNames();
        if (serverNames != null && serverNames.size() > 0) {
            OUTER: for (SNIServerName snisn : serverNames) {
                String hostname = new String(snisn.getEncoded(), "UTF-8");
                for (int i = 0; i < dnsNames.size(); i++)
                    if (dnsNames.get(i).matcher(hostname).matches()) {
                        sslContext = sslContexts.get(i);
                        break OUTER;
                    }
            }
            if (sslContext == null) {
                // no hostname matched: send 'unrecognized_name' alert and close socket

                byte[] alert_unrecognized_name = { 21 /* alert */, 3, 1 /* TLS 1.0 */, 0,
                        2 /* length: 2 bytes */, 2 /* fatal */, 112 /* unrecognized_name */ };

                try {
                    socket.getOutputStream().write(alert_unrecognized_name);
                } finally {
                    socket.close();
                }

                StringBuilder hostname = null;
                for (SNIServerName snisn : serverNames) {
                    if (hostname == null)
                        hostname = new StringBuilder();
                    else
                        hostname.append(", ");
                    hostname.append(new String(snisn.getEncoded(), "UTF-8"));
                }

                throw new RuntimeException(
                        "no certificate configured (sending unrecognized_name alert) for hostname \"" + hostname
                                + "\"");
            }
        }
    }

    // no Server Name Indication used by the client: fall back to first sslContext
    if (sslContext == null)
        sslContext = sslContexts.get(0);

    SSLSocketFactory serviceSocketFac = sslContext.getSocketFactory();

    ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, position);

    SSLSocket serviceSocket;
    // "serviceSocket = (SSLSocket)serviceSocketFac.createSocket(socket, bais, true);" only compileable with Java 1.8
    try {
        serviceSocket = (SSLSocket) createSocketMethod.invoke(serviceSocketFac,
                new Object[] { socket, bais, true });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    sslContext.applyCiphers(serviceSocket);
    if (sslContext.getProtocols() != null) {
        serviceSocket.setEnabledProtocols(sslContext.getProtocols());
    } else {
        String[] protocols = serviceSocket.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        serviceSocket.setEnabledProtocols(set.toArray(new String[0]));
    }
    serviceSocket.setWantClientAuth(sslContext.isWantClientAuth());
    serviceSocket.setNeedClientAuth(sslContext.isNeedClientAuth());

    return serviceSocket;
}

From source file:nl.b3p.commons.security.aselect.ASelectAgentClient.java

public Map performRequest(Map params) throws IOException {

    StringBuffer request = new StringBuffer("");
    Iterator i = params.entrySet().iterator();
    boolean first = true;
    while (i.hasNext()) {
        if (!first) {
            request.append("&");
        } else {/*from   w  w  w  . jav a 2s .c  o  m*/
            first = false;
        }

        Map.Entry entry = (Map.Entry) i.next();
        String key = entry.getKey().toString();
        String value = entry.getValue().toString();

        /* workaround voor bug in Agent waardoor deze het request niet
         * URL-decodeert.
         * Zie http://nic.surfnet.nl/scripts/wa.exe?A1=ind0503&L=a-select#4
         */
        if (!agentDecodeBug) {
            key = URLEncoder.encode(key, charset);
            value = URLEncoder.encode(key, charset);
        }
        request.append(key).append("=").append(value);
    }
    request.append(ASELECT_AGENT_EOL);

    String requestString = request.toString();

    log.debug("connecting to agent");
    Socket socket = new Socket(host, port);

    Map result;
    try {
        log.debug("request: " + requestString);
        socket.getOutputStream().write(requestString.getBytes());

        String response = (new BufferedReader(new InputStreamReader(socket.getInputStream(), charset)))
                .readLine();
        log.debug("response: " + response);

        result = ASelectUtils.parseQueryString(response, charset);
        result.put("complete_response", response);
    } finally {
        socket.close();
    }
    return result;
}

From source file:org.freewheelschedule.freewheel.controlserver.ControlThread.java

private void runJob(String hostname, Job jobToRun) throws IOException {
    log.debug("Connecting to the RemoteWorker to run a command");
    Socket remoteWorker = new Socket(jobToRun.getExecutingServer().getName(),
            jobToRun.getExecutingServer().getPort().intValue());

    PrintWriter command = new PrintWriter(remoteWorker.getOutputStream(), true);
    BufferedReader result = new BufferedReader(new InputStreamReader(remoteWorker.getInputStream()));

    if (workerAwaitingCommand(result, command, hostname) && jobToRun instanceof CommandJob) {
        if (!sendCommandToExecute(jobToRun, result, command)) {
            log.error("Job not queued properly");
        } else {//from  ww w  . j ava2 s.  co m
            log.error("Unexpected response from RemoteClient");
        }
    }
}

From source file:com.bitsofproof.supernode.core.IRCDiscovery.java

@Override
public List<InetSocketAddress> discover() {
    List<InetSocketAddress> al = new ArrayList<InetSocketAddress>();

    try {/*from   ww  w . ja v a 2  s  .c o m*/
        log.trace("Connect to IRC server " + server);
        Socket socket = new Socket(server, port);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

        String[] answers = new String[] { "Found your hostname", "using your IP address instead",
                "Couldn't look up your hostname", "ignoring hostname" };
        String line;
        boolean stop = false;
        while (!stop && (line = reader.readLine()) != null) {
            log.trace("IRC receive " + line);
            for (int i = 0; i < answers.length; ++i) {
                if (line.contains(answers[i])) {
                    stop = true;
                    break;
                }
            }
        }

        String nick = "bop" + new SecureRandom().nextInt(Integer.MAX_VALUE);
        writer.println("NICK " + nick);
        writer.println("USER " + nick + " 8 * : " + nick);
        writer.flush();
        log.trace("IRC send: I am " + nick);

        while ((line = reader.readLine()) != null) {
            log.trace("IRC receive " + line);
            if (hasCode(line, new String[] { " 004 ", " 433 " })) {
                break;
            }
        }
        log.trace("IRC send: joining " + channel);
        writer.println("JOIN " + channel);
        writer.println("NAMES");
        writer.flush();
        while ((line = reader.readLine()) != null) {
            log.trace("IRC receive " + line);
            if (hasCode(line, new String[] { " 353 " })) {
                StringTokenizer tokenizer = new StringTokenizer(line, ":");
                String t = tokenizer.nextToken();
                if (tokenizer.hasMoreElements()) {
                    t = tokenizer.nextToken();
                }
                tokenizer = new StringTokenizer(t);
                tokenizer.nextToken();
                while (tokenizer.hasMoreTokens()) {
                    String w = tokenizer.nextToken().substring(1);
                    if (!tokenizer.hasMoreElements()) {
                        continue;
                    }
                    try {
                        byte[] m = ByteUtils.fromBase58WithChecksum(w);
                        byte[] addr = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff, 0, 0,
                                0, 0 };
                        System.arraycopy(m, 0, addr, 12, 4);
                        al.add(new InetSocketAddress(InetAddress.getByAddress(addr), chain.getPort()));
                    } catch (ValidationException e) {
                        log.trace(e.toString());
                    }
                }
            }
            if (hasCode(line, new String[] { " 366 " })) {
                break;
            }
        }
        writer.println("PART " + channel);
        writer.println("QUIT");
        writer.flush();
        socket.close();
    } catch (UnknownHostException e) {
        log.error("Can not find IRC server " + server, e);
    } catch (IOException e) {
        log.error("Can not use IRC server " + server, e);
    }

    return al;
}

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

@Test
public void testMultipleMessages() throws IOException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(/*from   ww w.j a v  a 2s .co  m*/
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    .withConnectedSocketTask(new TcpConnectTestHandler()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    String message2 = "this is message2";
    try {
        Socket socket = new Socket("localhost", 1111);
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

        // message1
        out.write((message1 + '\n' + message2 + '\n').getBytes(StandardCharsets.UTF_8));
        String messageRead1 = reader.readLine();
        Assert.assertEquals(message1, messageRead1);
        String messageRead2 = reader.readLine();
        Assert.assertEquals(message2, messageRead2);

        // quit
        out.write("quit\n".getBytes(StandardCharsets.UTF_8));
        String finalMessage = reader.readLine();
        Assert.assertNull(finalMessage);
    } finally {
        simpleNbServer.shutdown();
    }
}

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

@Test
public void testReadTimeout() throws IOException, InterruptedException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111)
                    .withNbServiceConfig(NbServiceConfig.Builder.builder().withIoTaskTimeoutMs(10l)
                            .withIoTaskTimeoutCheckPeriodMs(2l).withSelectorTimeoutMs(2l).build())
                    .build())/*from  www.j  ava 2s.c o  m*/
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    .withConnectedSocketTask(new TcpConnectTestHandler()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    try {
        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((message1 + '\n').getBytes(StandardCharsets.UTF_8));
        reader.readLine();
        // message1
        Thread.sleep(100);
        String nextLine = null;
        try {
            out.write((message1 + '\n').getBytes(StandardCharsets.UTF_8));
            nextLine = reader.readLine();
        } catch (SocketException e) {
        }
        Assert.assertNull(nextLine);
    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:LCModels.MessageListener.java

public void run() {
    /* Keep Thread running */
    while (true) {
        try {// ww w .ja v  a 2  s  . c  om
            /* Accept connection on server */
            Socket serverSocket = server.accept();
            /* DataInputStream to get message sent by client program */
            DataInputStream in = new DataInputStream(serverSocket.getInputStream());
            /* We are receiving message in JSON format from client. Parse String to JSONObject */
            JSONObject clientMessage = new JSONObject(in.readUTF());

            /* Flag to check chat window is opened for user that sent message */
            boolean flagChatWindowOpened = false;
            /* Reading Message and Username from JSONObject */
            String userName = clientMessage.get("Username").toString();
            String message = clientMessage.getString("Message").toString();

            /* Get list of Frame/Windows opened by mainFrame.java */
            for (Frame frame : Frame.getFrames()) {
                /* Check Frame/Window is opened for user */
                if (frame.getTitle().equals(userName)) {
                    /* Frame/ Window is already opened */
                    flagChatWindowOpened = true;
                    /* Get instance of ChatWindow */
                    ChatWindowUI chatWindow = (ChatWindowUI) frame;
                    /* Get previous messages from TextArea */
                    String previousMessage = chatWindow.getMessageArea().getText();
                    /* Set message to TextArea with new message */
                    chatWindow.getMessageArea().setText(previousMessage + "\n" + userName + ": " + message);
                }
            }

            /* ChatWindow is not open for user sent message to server */
            if (!flagChatWindowOpened) {
                /* Create an Object of ChatWindow */
                ChatWindowUI chatWindow = new ChatWindowUI();
                /**
                 * We are setting title of window to identify user for next
                 * message we gonna receive You can set hidden value in
                 * ChatWindow.java file.
                 */
                chatWindow.setTitle(userName);
                /* Set message to TextArea */
                chatWindow.getMessageArea().setText(message);
                /* Make ChatWindow visible */
                chatWindow.setVisible(true);
            }

            /* Get DataOutputStream of client to repond */
            DataOutputStream out = new DataOutputStream(serverSocket.getOutputStream());
            /* Send response message to client */
            out.writeUTF("Received from " + clientMessage.get("Username").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

@Test
public void testEchoServer() throws IOException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(/*from w ww  .  j  a  va  2 s. c o m*/
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            .withConnectorFactory(TcpConnectorFactory.Builder.builder()
                    .withConnectedSocketTask(new TcpConnectTestHandler()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    String message2 = "this is message2";
    try {
        Socket socket = new Socket("localhost", 1111);
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

        // message1
        out.write((message1 + '\n').getBytes(StandardCharsets.UTF_8));
        String messageRead1 = reader.readLine();
        Assert.assertEquals(message1, messageRead1);

        // message2
        out.write((message2 + '\n').getBytes(StandardCharsets.UTF_8));
        String messageRead2 = reader.readLine();
        Assert.assertEquals(message2, messageRead2);

        // quit
        out.write("quit\n".getBytes(StandardCharsets.UTF_8));
        String finalMessage = reader.readLine();
        Assert.assertNull(finalMessage);
    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:demo.socket.pool.SocketsPool.java

private PooledSocketConn createConn(boolean printLog) throws IOException {

    Socket s = new Socket(host, port);
    if (socketSoTimeout != null)
        s.setSoTimeout(socketSoTimeout);

    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    if (printLog)
        log.info("Connected to " + host + ":" + port + "." + " Pool props [" + "maxActiveConnections="
                + poolMaximumActiveConnections + ", maxIdleConnections=" + poolMaximumIdleConnections
                + ", maxCheckoutTime=" + poolMaximumCheckoutTime + ", timeToWait=" + poolTimeToWait + "]");
    return new PooledSocketConn(s, is, os, this);
}

From source file:it.anyplace.sync.client.protocol.rp.RelayClient.java

public RelayConnection openConnectionSessionMode(final SessionInvitation sessionInvitation) throws Exception {
    logger.debug("connecting to relay = {}:{} (session mode)", sessionInvitation.getAddress(),
            sessionInvitation.getPort());
    final Socket socket = new Socket(sessionInvitation.getAddress(), sessionInvitation.getPort());
    RelayDataInputStream in = new RelayDataInputStream(socket.getInputStream());
    RelayDataOutputStream out = new RelayDataOutputStream(socket.getOutputStream());
    try {//  w  ww .jav a2 s  . co m
        {
            logger.debug("sending join session request, session key = {}", sessionInvitation.getKey());
            byte[] key = BaseEncoding.base16().decode(sessionInvitation.getKey());
            int lengthOfKey = key.length;
            out.writeHeader(JOIN_SESSION_REQUEST, 4 + lengthOfKey);
            out.writeInt(lengthOfKey);
            out.write(key);
            out.flush();
        }
        {
            logger.debug("reading relay response");
            MessageReader messageReader = in.readMessage();
            checkArgument(messageReader.getType() == RESPONSE);
            Response response = messageReader.readResponse();
            logger.debug("response = {}", response);
            checkArgument(response.getCode() == RESPONSE_SUCCESS_CODE, "response code = %s (%s) expected %s",
                    response.getCode(), response.getMessage(), RESPONSE_SUCCESS_CODE);
            logger.debug("relay connection ready");
        }
        return new RelayConnection() {
            @Override
            public Socket getSocket() {
                return socket;
            }

            @Override
            public boolean isServerSocket() {
                return sessionInvitation.isServerSocket();
            }

        };
    } catch (Exception ex) {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(socket);
        throw ex;
    }
}