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:edu.stanford.epadd.launcher.Main.java

@Override
public void run() {
    out.println("*** running jetty 'stop' thread");
    Socket accept;
    try {/*from   www . ja va2 s . c  o m*/
        accept = socket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        // wait for a readline
        String line = reader.readLine();
        // any input received, stop the server
        jettyServer.stop();
        out.println("*** Stopped the Jetty embedded web server. received: " + line);
        accept.close();
        socket.close();
        System.exit(1); // we need to explicitly system.exit because we now use Swing (due to system tray, etc).
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.undertow.server.handlers.ReceiverTestCase.java

@Test
public void testAsyncReceiveWholeBytesFailed() throws Exception {
    EXCEPTIONS.clear();// www  . j av  a 2  s.c om
    Socket socket = new Socket();
    socket.connect(DefaultServer.getDefaultServerAddress());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; ++i) {
        sb.append("hello world\r\n");
    }
    //send a large request that is too small, then kill the socket
    String request = "POST /fullbytes HTTP/1.1\r\nHost:localhost\r\nContent-Length:" + sb.length() + 100
            + "\r\n\r\n" + sb.toString();
    OutputStream outputStream = socket.getOutputStream();

    outputStream.write(request.getBytes("US-ASCII"));
    socket.getInputStream().close();
    outputStream.close();

    IOException e = EXCEPTIONS.poll(2, TimeUnit.SECONDS);
    Assert.assertNotNull(e);

}

From source file:com.hijacker.FeedbackDialog.java

void attemptSend() {
    feedbackView.setError(null);/*from  w  ww  . ja va2  s  .c om*/
    if (!internetAvailable(FeedbackDialog.this.getActivity())) {
        Log.d("HIJACKER/SendLog", "No internet connection");
        Snackbar.make(dialogView, getString(R.string.no_internet), Snackbar.LENGTH_SHORT).show();
        return;
    }

    final String feedback = feedbackView.getText().toString();
    if (feedback.equals("")) {
        feedbackView.setError(getString(R.string.field_required));
        feedbackView.requestFocus();
        return;
    }
    final String email = emailView.getText().toString();
    if (!email.equals("")) {
        pref_edit.putString("user_email", email);
        pref_edit.commit();
    }

    progress.setIndeterminate(true);

    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            FeedbackDialog.this.setCancelable(false);
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    progress.setIndeterminate(false);
                }
            };
            Socket socket = connect();
            if (socket == null) {
                runInHandler(runnable);
                Snackbar.make(dialogView, getString(R.string.server_error), Snackbar.LENGTH_SHORT).show();
                return;
            }

            try {
                PrintWriter in = new PrintWriter(socket.getOutputStream());
                BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                in.print(REQ_FEEDBACK + '\n');
                in.flush();

                String buffer;
                buffer = out.readLine();
                if (buffer != null) {
                    if (!buffer.equals(ANS_POSITIVE)) {
                        runInHandler(runnable);
                        Snackbar.make(dialogView, getString(R.string.server_denied), Snackbar.LENGTH_SHORT)
                                .show();
                        return;
                    }
                } else {
                    runInHandler(runnable);
                    Snackbar.make(dialogView, getString(R.string.connection_closed), Snackbar.LENGTH_SHORT)
                            .show();
                    return;
                }

                in.print("Hijacker feedback - " + new Date().toString() + "\n");
                in.print("User email: " + email + '\n');
                in.print("App version: " + versionName + " (" + versionCode + ")\n");
                in.print("Android version: " + Build.VERSION.SDK_INT + '\n');
                in.print("Device model: " + deviceModel + '\n');
                in.print("\nFeedback:\n");
                in.print(feedback + '\n');
                in.print("EOF\n");
                in.flush();

                if (report != null && include_report.isChecked()) {
                    in.print(REQ_REPORT + '\n');
                    in.flush();

                    buffer = out.readLine();
                    if (buffer != null) {
                        if (!buffer.equals(ANS_POSITIVE)) {
                            Snackbar.make(dialogView, getString(R.string.server_denied), Toast.LENGTH_SHORT)
                                    .show();
                            runInHandler(runnable);
                            return;
                        }
                    } else {
                        Snackbar.make(dialogView, getString(R.string.connection_closed), Toast.LENGTH_SHORT)
                                .show();
                        runInHandler(runnable);
                        return;
                    }

                    BufferedReader fileReader = new BufferedReader(new FileReader(report));

                    in.print("User email: " + email + '\n');
                    in.flush();
                    buffer = fileReader.readLine();
                    while (buffer != null) {
                        in.print(buffer + '\n');
                        in.flush();
                        buffer = fileReader.readLine();
                    }
                    in.print("EOF\n");
                    in.flush();
                }
                in.print(REQ_EXIT + '\n');
                in.flush();

                in.close();
                out.close();
                socket.close();
                dismissAllowingStateLoss();
            } catch (IOException e) {
                Log.e("HIJACKER/FeedbackOnSend", e.toString());
                Snackbar.make(dialogView, getString(R.string.unknown_error), Snackbar.LENGTH_SHORT).show();
            } finally {
                runInHandler(runnable);
                FeedbackDialog.this.setCancelable(true);
            }
        }
    }).start();
}

From source file:com.example.blackberry.agoodandroidsample.SocketFragment.java

/**
 * Creates a socket connection to developer.BlackBerry.com:80.
 * @return An InputStream retrieved from a successful HttpURLConnection.
 * @throws java.io.IOException//  ww  w .  j  a  v a 2  s  . c o  m
 */
private String doSocket() throws IOException {

    Socket socket = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        socket = new Socket("developer.blackberry.com", 80);
        String response = "";

        //We'll make an HTTP request over the socket connection.
        String output = "GET http://developer.blackberry.com/ HTTP/1.1\r\n"
                + "Host: developer.blackberry.com:80\r\n" + "Connection: close\r\n" + "\r\n";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];

        int bytesRead;
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();

        outputStream.write(output.getBytes());

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
            response += byteArrayOutputStream.toString("UTF-8");

            if (response.length() > 1000) {
                //Stop reading after we've reached 1000 characters.
                break;
            }
        }

        //Close all connections.
        inputStream.close();
        outputStream.close();
        byteArrayOutputStream.close();

        return response;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }

        if (outputStream != null) {
            outputStream.close();
        }

        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.smartmarmot.orabbix.Sender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    //message.append(Base64.encode(key));
    message.append(base64Encode(key));/* ww w .  ja va 2 s  . c o m*/
    message.append(middle);
    //message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    if (log.isDebugEnabled()) {
        SmartLogger.logThis(Level.DEBUG, "sending " + message);
    }

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    Enumeration<String> serverlist = zabbixServers.keys();

    while (serverlist.hasMoreElements()) {
        String zabbixServer = serverlist.nextElement();
        try {
            zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            if (log.isDebugEnabled()) {
                SmartLogger.logThis(Level.DEBUG, "received " + new String(response));
            }
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                SmartLogger.logThis(Level.WARN,
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + "  on port "
                    + zabbixServers.get(zabbixServer));
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

From source file:org.apache.hadoop.hdfs.TestDataTransferProtocol.java

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf.//  w  w w  .j  a v a 2 s . com
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, HdfsConstants.READ_TIMEOUT);
        sock.setSoTimeout(HdfsConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}

From source file:com.lithium.flow.shell.sshj.SshjTunnel.java

private void accept(@Nonnull Socket socket) throws IOException {
    log.debug("connection from {}", socket.getRemoteSocketAddress());

    AbstractDirectChannel channel = new AbstractDirectChannel(connection, "direct-tcpip") {
        @Override/*www .j  av  a 2 s . c o  m*/
        @Nonnull
        protected SSHPacket buildOpenReq() {
            return super.buildOpenReq().putString(tunneling.getHost()).putUInt32(tunneling.getPort())
                    .putString(getHost()).putUInt32(server.getLocalPort());
        }
    };
    channel.open();

    socket.setSendBufferSize(channel.getLocalMaxPacketSize());
    socket.setReceiveBufferSize(channel.getRemoteMaxPacketSize());
    Event<IOException> soc2chan = new StreamCopier(socket.getInputStream(), channel.getOutputStream())
            .bufSize(channel.getRemoteMaxPacketSize()).spawnDaemon("soc2chan");
    Event<IOException> chan2soc = new StreamCopier(channel.getInputStream(), socket.getOutputStream())
            .bufSize(channel.getLocalMaxPacketSize()).spawnDaemon("chan2soc");
    SocketStreamCopyMonitor.monitor(5, TimeUnit.SECONDS, soc2chan, chan2soc, channel, socket);
}

From source file:bankingclient.DKFrame.java

public DKFrame(MainFrame vmain) {
    initComponents();/*from   w w w .  jav a  2  s . com*/
    this.main = vmain;
    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField3.setText("");
    this.jTextField4.setText("");
    this.jTextField5.setText("");
    this.setVisible(false);
    jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jTextField2.getText().equals(jTextField3.getText())
                    && NumberUtils.isNumber(jTextField4.getText())
                    && NumberUtils.isNumber(jTextField5.getText())) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    String cusName = jTextField1.getText();
                    String pass = jTextField2.getText();
                    String sdt = jTextField4.getText();
                    String cmt = jTextField5.getText();
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(1);
                    dout.writeUTF(cusName + "\n" + pass + "\n" + sdt + "\n" + cmt);
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da dang ki tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "dang ki tai khoan khong thanh cong");

                    }
                    client.close();
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
                main.setVisible(true);
                DKFrame.this.setVisible(false);

            } else {
                JOptionPane.showMessageDialog(rootPane, "Nhap thong tin sai, moi nhap lai");
            }
        }
    });
    jButton2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DKFrame.this.setVisible(false);
        }
    });
}

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 www.j ava 2 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.chinamobile.bcbsp.pipes.BinaryProtocol.java

/**
 * Create a proxy object that will speak the binary protocol on a socket.
 * Upward messages are passed on the specified handler and downward downward
 * messages are public methods on this object.
 * @param sock/*from   w w w .  j  a  v  a2 s  .  c  o  m*/
 *        The socket to communicate on.
 * @param handler
 *        The handler for the received messages.
 *
 * @throws IOException e
 */

public BinaryProtocol(Socket sock, UpwardProtocol handler) throws IOException {
    OutputStream raw = sock.getOutputStream();
    // If we are debugging, save a copy of the downlink commands to a file
    // just for test
    // raw = new TeeOutputStream("downlink.txt", raw);
    outPutstream = new DataOutputStream(new BufferedOutputStream(raw, BUFFER_SIZE));
    uplink = new UplinkReaderThread(sock.getInputStream(), handler);
    uplink.setName("pipe-uplink-handler");
    uplink.start();
}