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:fitnesse.http.ResponseParser.java

public static ResponseParser performHttpRequest(String hostname, int hostPort, RequestBuilder builder)
        throws IOException {
    Socket socket = new Socket(hostname, hostPort);
    OutputStream socketOut = socket.getOutputStream();
    InputStream socketIn = socket.getInputStream();
    builder.send(socketOut);/*from ww w. ja  v  a 2s . c  o  m*/
    socketOut.flush();
    try {
        return new ResponseParser(socketIn);
    } finally {
        socketOut.close();
        socket.close();
    }
}

From source file:Main.java

public static int readNetSocketBytes(Socket socket, int timeoutMS, byte[] buffer, int maxLen) throws Exception {
    int ret = 0, timeout = -2, bytesAvailable = 0, curRead = 0, waitCount = 0;
    boolean haveData = false;

    InputStream is = socket.getInputStream();
    while (timeout < timeoutMS) {
        bytesAvailable = is.available();
        if (bytesAvailable > 0) {
            haveData = true;/*  w ww .j  av a 2 s.c o  m*/
            waitCount = 0;
            curRead = ((bytesAvailable > (maxLen - ret)) ? (maxLen - ret) : bytesAvailable);
            curRead = is.read(buffer, ret, curRead);
            ret += curRead;
            if (ret >= maxLen) {
                return ret;
            }
        } else {
            if (timeoutMS == -1) {
                break;
            }
            Thread.sleep(10);
            if (timeoutMS != 0) {
                timeout += 10;
            } else if ((haveData == true) && (waitCount++ > HAVE_DATA_WAIT_RETRIES)) {
                break;
            }
        }
    }
    return ret;
}

From source file:com.zack6849.alphabot.api.Utils.java

public static String checkServerStatus(InetAddress i, int port) {
    String returns = "Error.";
    try {/* ww w.  j av  a 2 s  .c om*/
        //wow...i never actually used the port argument?
        Socket s = new Socket(i, port);
        DataInputStream SS_BF = new DataInputStream(s.getInputStream());
        DataOutputStream d = new DataOutputStream(s.getOutputStream());
        d.write(new byte[] { (byte) 0xFE, (byte) 0x01 });
        SS_BF.readByte();
        short length = SS_BF.readShort();
        StringBuilder sb = new StringBuilder();
        for (int in = 0; in < length; in++) {
            char ch = SS_BF.readChar();
            sb.append(ch);
        }
        String all = sb.toString().trim();
        System.out.println(all);
        String[] args1 = all.split("\u0000");
        if (args1[3].contains("")) {
            returns = "MOTD: " + args1[3].replaceAll("[a-m]", "").replaceAll("[1234567890]", "")
                    + "   players: [" + args1[4] + "/" + args1[5] + "]";
        } else {
            returns = "MOTD: " + args1[3] + "   players: [" + args1[4] + "/" + args1[5] + "]";
        }
    } catch (UnknownHostException e1) {
        returns = "the host you specified is unknown. check your settings.";
    } catch (IOException e1) {
        returns = "sorry, we couldn't reach this server, make sure that the server is up and has query enabled.";
    }
    return returns;
}

From source file:mainserver.Server.java

public static String getMessage(Socket clientSocket) {
    String message = null;/*from w ww.j  ava 2  s . co m*/
    try {
        BufferedReader bufferedReaderInput = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
        message = bufferedReaderInput.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return message;
}

From source file:SimpleProxyServer.java

/**
 * runs a single-threaded proxy server on
 * the specified local port. It never returns.
 *///from  w w w  .  j a v a2  s.com
public static void runServer(String host, int remoteport, int localport) throws IOException {
    // Create a ServerSocket to listen for connections with
    ServerSocket ss = new ServerSocket(localport);

    final byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (true) {
        Socket client = null, server = null;
        try {
            // Wait for a connection on the local port
            client = ss.accept();

            final InputStream streamFromClient = client.getInputStream();
            final OutputStream streamToClient = client.getOutputStream();

            // Make a connection to the real server.
            // If we cannot connect to the server, send an error to the
            // client, disconnect, and continue waiting for connections.
            try {
                server = new Socket(host, remoteport);
            } catch (IOException e) {
                PrintWriter out = new PrintWriter(streamToClient);
                out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
                out.flush();
                client.close();
                continue;
            }

            // Get server streams.
            final InputStream streamFromServer = server.getInputStream();
            final OutputStream streamToServer = server.getOutputStream();

            // a thread to read the client's requests and pass them
            // to the server. A separate thread for asynchronous.
            Thread t = new Thread() {
                public void run() {
                    int bytesRead;
                    try {
                        while ((bytesRead = streamFromClient.read(request)) != -1) {
                            streamToServer.write(request, 0, bytesRead);
                            streamToServer.flush();
                        }
                    } catch (IOException e) {
                    }

                    // the client closed the connection to us, so close our
                    // connection to the server.
                    try {
                        streamToServer.close();
                    } catch (IOException e) {
                    }
                }
            };

            // Start the client-to-server request thread running
            t.start();

            // Read the server's responses
            // and pass them back to the client.
            int bytesRead;
            try {
                while ((bytesRead = streamFromServer.read(reply)) != -1) {
                    streamToClient.write(reply, 0, bytesRead);
                    streamToClient.flush();
                }
            } catch (IOException e) {
            }

            // The server closed its connection to us, so we close our
            // connection to our client.
            streamToClient.close();
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            try {
                if (server != null)
                    server.close();
                if (client != null)
                    client.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.splout.db.benchmark.TCPTest.java

public static void tcpTest(String file, String table)
        throws UnknownHostException, IOException, InterruptedException, JSONSerDeException {
    final TCPServer server = new TCPServer(8888, file, table);

    Thread t = new Thread() {
        @Override//from  w w w  . java2  s  .c  om
        public void run() {
            server.serve();
        }
    };
    t.start();

    while (!server.isServing()) {
        Thread.sleep(100);
    }

    Socket clientSocket = new Socket("localhost", 8888);
    DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));

    try {
        do {
            // Read a record
            inFromServer.readUTF();
            inFromServer.readInt();
            inFromServer.readDouble();
            inFromServer.readUTF();
        } while (true);
    } catch (Throwable th) {
        th.printStackTrace();
    }

    clientSocket.close();
    server.stop();
    t.interrupt();
}

From source file:org.apache.htrace.impl.HTracedProcess.java

private static StartupNotificationData readStartupNotification(ServerSocket listener) throws IOException {
    Socket socket = listener.accept();
    try {/* w w w .  ja v a  2 s.  c o m*/
        InputStream in = socket.getInputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        StartupNotificationData data = objectMapper.readValue(in, StartupNotificationData.class);
        return data;
    } finally {
        socket.close();
    }
}

From source file:eu.stratosphere.nephele.net.NetUtils.java

/**
 * Returns InputStream for the socket. If the socket has an associated
 * SocketChannel then it returns a {@link SocketInputStream} with the given timeout. If the socket does not
 * have a channel, {@link Socket#getInputStream()} is returned. In the later
 * case, the timeout argument is ignored and the timeout set with {@link Socket#setSoTimeout(int)} applies for
 * reads.<br>//  www  . j av a  2s .c  o m
 * <br>
 * Any socket created using socket factories returned by {@link #NetUtils},
 * must use this interface instead of {@link Socket#getInputStream()}.
 * 
 * @see Socket#getChannel()
 * @param socket
 * @param timeout
 *        timeout in milliseconds. This may not always apply. zero
 *        for waiting as long as necessary.
 * @return InputStream for reading from the socket.
 * @throws IOException
 */
public static InputStream getInputStream(Socket socket, long timeout) throws IOException {
    return (socket.getChannel() == null) ? socket.getInputStream() : new SocketInputStream(socket, timeout);
}

From source file:org.apache.flink.runtime.net.NetUtils.java

/**
 * Returns InputStream for the socket. If the socket has an associated
 * SocketChannel then it returns a {@link SocketInputStream} with the given timeout. If the socket does not
 * have a channel, {@link Socket#getInputStream()} is returned. In the later
 * case, the timeout argument is ignored and the timeout set with {@link Socket#setSoTimeout(int)} applies for
 * reads.<br>/*  w  w w  . ja v  a 2s.  c  om*/
 * <br>
 * Any socket created using socket factories returned by {@link #NetUtils},
 * must use this interface instead of {@link Socket#getInputStream()}.
 * 
 * @see Socket#getChannel()
 * @param socket
 * @param timeout
 *        timeout in milliseconds. This may not always apply. zero
 *        for waiting as long as necessary.
 * @return InputStream for reading from the socket.
 * @throws IOException
 */
@SuppressWarnings("resource")
public static InputStream getInputStream(Socket socket, long timeout) throws IOException {
    return (socket.getChannel() == null) ? socket.getInputStream() : new SocketInputStream(socket, timeout);
}

From source file:Messenger.TorLib.java

/**
 * This method creates a socket to the target host and port using TorSocketPre, then reads
 * the SOCKS information.//from w w  w  .  jav  a  2  s.com
 * @param targetHostname Hostname of destination host.
 * @param targetPort Port on remote destination host.
 * @return Fully initialized TCP Socket that tunnels to the target Host/Port via the Tor Proxy host/port.
 * @throws IOException when Socket and Read/Write exceptions occur.
 */
static Socket TorSocket(String targetHostname, int targetPort) throws IOException {
    Socket s = TorSocketPre(targetHostname, targetPort, TOR_CONNECT);
    DataInputStream is = new DataInputStream(s.getInputStream());

    // only the status is useful on a TOR CONNECT
    byte version = is.readByte();
    byte status = is.readByte();
    if (status != (byte) 90) {
        //failed for some reason, return useful exception
        throw (new IOException(ParseSOCKSStatus(status)));
    }
    //      System.out.println("status: "+ParseSOCKSStatus(status));
    int port = is.readShort();
    int ipAddr = is.readInt();
    return (s);
}