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.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//from w  w w.j a  v  a  2s. c om

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

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

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

    OnSourcerListener listener = new OnSourcerListener() {

        @Override//from w w w .  j  a v  a  2 s  .c  o m
        public void onError(String string) {
            onConnected = true;
        }

        @Override
        public void onDisconnected(boolean connected) {
        }

        @Override
        public void onConnected() {
        }
    };

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

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.replay(sockMock);

    shoutcast.setOnSourcerListener(listener);
    shoutcast.start(sockMock);

    Assert.assertTrue(onConnected);
}

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

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

    OnSourcerListener listener = new OnSourcerListener() {

        @Override//w  w  w . j a v a  2 s . c  o m
        public void onError(String string) {
        }

        @Override
        public void onDisconnected(boolean connected) {
        }

        @Override
        public void onConnected() {
            onConnected = true;
        }
    };

    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.replay(sockMock);

    shoutcast.setOnSourcerListener(listener);
    shoutcast.start(sockMock);

    Assert.assertTrue(onConnected);
}

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

private void initializeIOStreams() throws IOException {
    if (passiveModeSocket != null) {
        transIs = passiveModeSocket.getInputStream();
        transOut = passiveModeSocket.getOutputStream();
    } else if (activeModeServerSocket != null) {
        Socket socket = activeModeServerSocket.accept();
        transIs = socket.getInputStream();
        transOut = socket.getOutputStream();
    } else {/*from   w w  w .  ja v  a2 s. c o  m*/
        throw new IOException("IO streams have not been initialized");
    }
}

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

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

    OnSourcerListener listener = new OnSourcerListener() {

        @Override// w  w w . j a  va 2  s .  c  o m
        public void onError(String string) {
            onConnected = true;
        }

        @Override
        public void onDisconnected(boolean connected) {
        }

        @Override
        public void onConnected() {
        }
    };

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

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.replay(sockMock);

    icecast.setOnSourcerListener(listener);
    icecast.start(sockMock);

    Assert.assertTrue(onConnected);
}

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

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

    OnSourcerListener listener = new OnSourcerListener() {

        @Override/*from ww  w.j a v  a2s . c  o m*/
        public void onError(String string) {
        }

        @Override
        public void onDisconnected(boolean connected) {
            onConnected = true;
        }

        @Override
        public void onConnected() {
        }
    };

    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.replay(sockMock);

    shoutcast.setOnSourcerListener(listener);

    boolean started = shoutcast.start(sockMock);
    Assert.assertTrue(started);

    boolean stopped = shoutcast.stop();
    Assert.assertTrue(stopped);

    Assert.assertTrue(onConnected);
}

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

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

    OnSourcerListener listener = new OnSourcerListener() {

        @Override//from  w  w  w .  ja  va 2 s  .co  m
        public void onError(String string) {
        }

        @Override
        public void onDisconnected(boolean connected) {
        }

        @Override
        public void onConnected() {
            onConnected = true;
        }
    };

    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.replay(sockMock);

    icecast.setOnSourcerListener(listener);
    icecast.start(sockMock);

    Assert.assertTrue(onConnected);
}

From source file:co.cask.cdap.gateway.router.NettyRouterTestBase.java

@Test(timeout = 10000)
public void testConnectionIdleTimeout() throws Exception {
    defaultServer2.cancelRegistration();

    String path = "/v2/ping";
    URI uri = new URI(resolveURI(Constants.Router.GATEWAY_DISCOVERY_NAME, path));
    Socket socket = getSocketFactory().createSocket(uri.getHost(), uri.getPort());
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    InputStream inputStream = socket.getInputStream();

    // make a request
    String firstLine = makeRequest(uri, out, inputStream);
    Assert.assertEquals("HTTP/1.1 200 OK\r", firstLine);

    // sleep for 500 ms below the configured idle timeout; the connection on server side should not get closed by then
    TimeUnit.MILLISECONDS.sleep(TimeUnit.SECONDS.toMillis(CONNECTION_IDLE_TIMEOUT_SECS) - 500);
    firstLine = makeRequest(uri, out, inputStream);
    Assert.assertEquals("HTTP/1.1 200 OK\r", firstLine);

    // sleep for 500 ms over the configured idle timeout; the connection on server side should get closed by then
    TimeUnit.MILLISECONDS.sleep(TimeUnit.SECONDS.toMillis(CONNECTION_IDLE_TIMEOUT_SECS) + 500);
    // Due to timeout the client connection will be closed, and hence this request should not go to the server
    makeRequest(uri, out, inputStream);//from  w  ww . j ava  2  s . c  o m

    // assert that the connection is closed on the server side
    Assert.assertEquals(2, defaultServer1.getNumRequests() + defaultServer2.getNumRequests());
    Assert.assertEquals(1, defaultServer1.getNumConnectionsOpened() + defaultServer2.getNumConnectionsOpened());
    Assert.assertEquals(1, defaultServer1.getNumConnectionsClosed() + defaultServer2.getNumConnectionsClosed());
}

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

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

    OnSourcerListener listener = new OnSourcerListener() {

        @Override//from ww  w .j  a  v a  2s.  c o  m
        public void onError(String string) {
        }

        @Override
        public void onDisconnected(boolean connected) {
            onConnected = true;
        }

        @Override
        public void onConnected() {
        }
    };

    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.replay(sockMock);

    icecast.setOnSourcerListener(listener);

    boolean started = icecast.start(sockMock);
    Assert.assertTrue(started);

    boolean stopped = icecast.stop();
    Assert.assertTrue(stopped);

    Assert.assertTrue(onConnected);
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 *//*  w  w  w.ja v a 2s. c o m*/
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

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