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.sk89q.craftapi.streaming.StreamingServerClient.java

/**
 * Construct the instance./* ww  w. j a  v a2s.  co  m*/
 * 
 * @param server
 * @param socket
 */
public StreamingServerClient(StreamingServer server, Socket socket) throws Throwable {
    this.server = server;
    this.socket = socket;

    random = SecureRandom.getInstance("SHA1PRNG");
    challenge = new byte[32];
    random.nextBytes(challenge);

    InputStreamReader inReader = new InputStreamReader(socket.getInputStream(), "utf-8");
    in = new BufferedReader(inReader);
    out = new PrintStream(socket.getOutputStream(), true, "utf-8");
}

From source file:com.yeetor.minitouch.Minitouch.java

private Thread startInitialThread(final String host, final int port) {
    Thread thread = new Thread(new Runnable() {
        @Override//from ww  w.  j a  va  2 s . c o  m
        public void run() {
            int tryTime = 200;
            while (true) {
                Socket socket = null;
                byte[] bytes = new byte[256];
                try {
                    socket = new Socket(host, port);
                    InputStream inputStream = socket.getInputStream();
                    OutputStream outputStream = socket.getOutputStream();
                    int n = inputStream.read(bytes);

                    if (n == -1) {
                        Thread.sleep(10);
                        socket.close();
                    } else {
                        minitouchSocket = socket;
                        minitouchOutputStream = outputStream;
                        onStartup(true);
                        break;
                    }
                } catch (Exception ex) {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    continue;
                }
                tryTime--;
                if (tryTime == 0) {
                    onStartup(false);
                    break;
                }
            }
        }
    });
    thread.start();
    return thread;
}

From source file:UniqueInstance.java

/**
 * Reoit un message d'une socket s'tant connecte au serveur d'coute. Si ce message est le message de l'instance
 * unique, l'application demande le focus.
 *
 * @param socket/*from w  w w .j a v a  2s.  c o m*/
 * Socket connect au serveur d'coute.
 */
private void receive(Socket socket) {
    Scanner sc = null;

    try {
        /* On n'coute que 5 secondes, si aucun message n'est reu, tant pis... */
        socket.setSoTimeout(5000);

        /* On dfinit un Scanner pour lire sur l'entre de la socket. */
        sc = new Scanner(socket.getInputStream());

        /* On ne lit qu'une ligne. */
        String s = sc.nextLine();

        /* Si cette ligne est le message de l'instance unique... */
        if (message.equals(s)) {
            /* On excute le code demand. */
            runOnReceive.run();
        }
    } catch (IOException e) {
        Logger.getLogger("UniqueInstance").warning("Lecture du flux d'entre de la socket chou.");
    } finally {
        if (sc != null) {
            sc.close();
        }
    }

}

From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java

private void runTest(ServerSocket listener, ProcessBuilder launcher, StatisticsMBean stats, byte[] jobData)
        throws IOException, InterruptedException {
    Process proc = launcher.start();

    //connect stdout and stderr to parent process streams
    if (log.isDebugEnabled()) {
        new PipeThread(proc.getInputStream(), System.out).start();
        new PipeThread(proc.getErrorStream(), System.err).start();
    } else {/*from  ww w  .  j  av  a  2s .c  o m*/
        NullOutput sink = new NullOutput();
        new PipeThread(proc.getInputStream(), sink).start();
        new PipeThread(proc.getErrorStream(), sink).start();
    }

    //wait for the incoming connection from the child process.
    Socket sock = listener.accept();
    try {
        //connection established, send the job.
        OutputStream os = sock.getOutputStream();
        os.write(jobData);
        os.flush();

        //read measurements back.
        DataInputStream dis = new DataInputStream(sock.getInputStream());
        for (long measure = dis.readLong(); measure >= 0; measure = dis.readLong())
            stats.add(measure);

        //send ack byte to tell the child proc its ok to hang up.
        os.write(1);
        os.flush();

    } finally {
        sock.close();
    }

    assertEquals("Child process ended successfully", 0, proc.waitFor());
}

From source file:Networking.Client.java

@Override
public void run() {
    Socket clientSocket;
    try {/*from ww  w  .  j ava  2s .c o  m*/
        while ((clientSocket = server.accept()) != null) {
            InputStream is = clientSocket.getInputStream();
            byte[] bytes = IOUtils.toByteArray(is);
            String received = (new String(bytes, "UTF-8"));

            if (received != null) {
                if (finishWriting && verified && !lenReceived && !allLenREceived) {
                    MsgLen = Integer.parseInt(received);
                    setLenReceived(true);
                } else if (finishWriting && verified && lenReceived && !allLenREceived) {
                    setLenReceived(false);
                    File fileForIV = new File("./read_iv.txt");
                    if (fileForIV.createNewFile()) {
                        System.out.println("File is created!");
                    }
                    downloadFiles(bytes, fileForIV, MsgLen);
                    decryptMessage(received, (int) fileForIV.length());

                } else if (received.contains("AKE")) {
                    this.node.setG_pow_y(new BigInteger(received.substring(3, received.length())));
                    this.node.setG_pow_y(this.node.getG_pow_y());
                    Calculateg_xy_mod();

                } else if (!IdentityReceived) {
                    idLen = Integer.parseInt(received);
                    IdentityReceived = true;

                } else {
                    if (!wroteToSig && !SigVerifiedFn && IdentityReceived) {
                        Hash_xy_mod();
                        signLen = Integer.parseInt(received);
                        wroteToSig = true;

                    } else if (wroteToSig && !finishWriting && !SigVerifiedFn && IdentityReceived) {
                        pubLen = Integer.parseInt(received);
                        SigVerifiedFn = true;

                    } else if (wroteToSig && !finishWriting && SigVerifiedFn && IdentityReceived
                            && !allLenREceived) {
                        hmacLen = Integer.parseInt(received);
                        allLenREceived = true;
                    } else if (allLenREceived) {
                        File fileForall = new File("./entire_read.txt");
                        if (fileForall.createNewFile()) {
                            System.out.println("File is created!");
                        }
                        downloadFiles(bytes, fileForall, idLen + signLen + pubLen + hmacLen);

                        FileInputStream all = new FileInputStream("./entire_read.txt");
                        byte[] id = new byte[idLen];
                        all.read(id);
                        otherIdentity = (new String(id, "UTF-8"));
                        sigToVerify = new byte[signLen];
                        all.read(sigToVerify);
                        PubToVerify = new byte[pubLen];
                        all.read(PubToVerify);
                        verified = SignatureVerification();
                        byte[] hmac = new byte[hmacLen];
                        all.read(hmac);
                        MacToVerify = (new String(hmac, "UTF-8"));
                        finishWriting = verifyMac();
                        allLenREceived = false;
                        all.close();

                        if (!verified || !finishWriting) {
                            writer.write("BUMMMMMERRRRR");
                            System.exit(1);
                        }
                    }

                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1Test.java

@Test
public void testConnectFails() throws IOException {
    Socket mock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("KO").getBytes());

    EasyMock.expect(mock.getOutputStream()).andReturn(out);
    EasyMock.expect(mock.getInputStream()).andReturn(in);
    EasyMock.replay(mock);// w  w w .  j  av  a 2 s  .c om

    boolean started = shoutcast.start(mock);

    Assert.assertFalse(started);
    Assert.assertFalse(shoutcast.isStarted());
}

From source file:com.supernovapps.audio.jstreamsourcer.IcecastTest.java

@Test
public void testConnectFails() throws IOException {
    Socket mock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("KO").getBytes());

    EasyMock.expect(mock.getOutputStream()).andReturn(out);
    EasyMock.expect(mock.getInputStream()).andReturn(in);
    EasyMock.replay(mock);/*from   w  w  w .  j  a  v a2 s  .co  m*/

    boolean started = icecast.start(mock);

    Assert.assertFalse(started);
    Assert.assertFalse(icecast.isStarted());
}

From source file:com.alibaba.wasp.zookeeper.ZKUtil.java

/**
 * Gets the statistics from the given server.
 *
 * @param server//from  w  w  w . j  a  va 2  s .  c o m
 *          The server to get the statistics from.
 * @param timeout
 *          The socket timeout to use.
 * @return The array of response strings.
 * @throws java.io.IOException
 *           When the socket communication fails.
 */
public static String[] getServerStats(String server, int timeout) throws IOException {
    String[] sp = server.split(":");
    if (sp == null || sp.length == 0) {
        return null;
    }

    String host = sp[0];
    int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;

    Socket socket = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    socket.connect(sockAddr, timeout);

    socket.setSoTimeout(timeout);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("stat");
    out.flush();
    ArrayList<String> res = new ArrayList<String>();
    while (true) {
        String line = in.readLine();
        if (line != null) {
            res.add(line);
        } else {
            break;
        }
    }
    socket.close();
    return res.toArray(new String[res.size()]);
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1Test.java

@Test
public void testConnectSuccess() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);/*from w ww .j  a v  a  2  s . c om*/

    boolean started = shoutcast.start(sockMock);

    Assert.assertTrue(started);
    Assert.assertTrue(shoutcast.isStarted());
}

From source file:at.sti2.sparkwave.ServerSocketThread.java

/**
 * TCP/IP Sparkwave Network Server/*  ww  w.j  a va  2  s  .c  om*/
 */
public void run() {

    try {

        //Open TCP/IP Server socket
        ServerSocket server = new ServerSocket(configuration.getPort());
        logger.info("Server: " + server);

        while (!Thread.interrupted()) {
            logger.info("Waiting for connection...");
            Socket sock = server.accept();
            logger.info("Connected: " + sock);

            //TODO Not every connection should cause a rebuild of the plugin chain. Should work with arbitrary many connections and failure resistent. re-use plugin threads and parser threads.

            InputStream socketStreamIn = sock.getInputStream();

            // PreProcessing Plugins to be loaded
            if (configuration.getPPPluginsConfig().size() == 2) {

                //TODO support arbitrary many plugins

                // Wiring: socketStreamIn --> (Plugin1) --> PipeOut1 --> PipeIn1
                final PipedOutputStream pipeOut1 = new PipedOutputStream();
                final PipedInputStream pipeIn1 = new PipedInputStream(pipeOut1);

                // Wiring: PipeIn1 --> (Plugin2) --> PipeOut2 --> PipeIn2
                final PipedOutputStream pipeOut2 = new PipedOutputStream();
                final PipedInputStream pipeIn2 = new PipedInputStream(pipeOut2);

                final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                // plugin configuration
                PPPluginConfig pluginConfig1 = configuration.getPPPluginsConfig().get(0);
                PreProcess plugin1 = instantiateAndConfigurePlugin(pluginConfig1, socketStreamIn, pipeOut1);

                PPPluginConfig pluginConfig2 = configuration.getPPPluginsConfig().get(1);
                PreProcess plugin2 = instantiateAndConfigurePlugin(pluginConfig2, pipeIn1, pipeOut2);

                // N3 Parser
                StreamParserThread sparkStreamParserThread = new StreamParserThread(pipeIn2, queues);

                // kick-off pre-process
                sparkwaveParserExecutor.execute(plugin1);
                sparkwaveParserExecutor.execute(plugin2);

                // kick-off parser
                sparkwaveParserExecutor.execute(sparkStreamParserThread);

            } else {

                StreamParserThread sparkStreamParserThread = new StreamParserThread(socketStreamIn, queues);

                // kick-off parser
                sparkwaveParserExecutor.execute(sparkStreamParserThread);

            }

        }

    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {

    }
}