Example usage for java.nio.channels SocketChannel socket

List of usage examples for java.nio.channels SocketChannel socket

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel socket.

Prototype

public abstract Socket socket();

Source Link

Document

Retrieves a socket associated with this channel.

Usage

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testByteArrayReadMulti() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    stream.write(ByteBuffer.wrap("bar".getBytes()));
    byte[] out = new byte[6];
    int n = stream.read(out);
    assertEquals(6, n);//from   w w  w  .  j  a v  a 2  s  . c  om
    assertEquals("foobar", new String(out));
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testByteArrayRead() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    byte[] out = new byte[2];
    int n = stream.read(out);
    assertEquals(2, n);//from w  ww. j  a v a 2s . c om
    assertEquals("fo", new String(out));
    out = new byte[2];
    n = stream.read(out);
    assertEquals(1, n);
    assertEquals("o\u0000", new String(out));
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void transferHeaders() throws Exception {
    Socket inSocket = mock(Socket.class);
    SocketChannel inChannel = mock(SocketChannel.class);
    when(inChannel.socket()).thenReturn(inSocket);

    TcpNioConnection inboundConnection = new TcpNioConnection(inChannel, true, false, nullPublisher, null);
    inboundConnection.setDeserializer(new MapJsonSerializer());
    MapMessageConverter inConverter = new MapMessageConverter();
    MessageConvertingTcpMessageMapper inMapper = new MessageConvertingTcpMessageMapper(inConverter);
    inboundConnection.setMapper(inMapper);
    final ByteArrayOutputStream written = new ByteArrayOutputStream();
    doAnswer(new Answer<Integer>() {

        @Override//from ww  w.j a va 2s  . co m
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            ByteBuffer buff = invocation.getArgument(0);
            byte[] bytes = written.toByteArray();
            buff.put(bytes);
            return bytes.length;
        }
    }).when(inChannel).read(any(ByteBuffer.class));

    Socket outSocket = mock(Socket.class);
    SocketChannel outChannel = mock(SocketChannel.class);
    when(outChannel.socket()).thenReturn(outSocket);
    TcpNioConnection outboundConnection = new TcpNioConnection(outChannel, true, false, nullPublisher, null);
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            ByteBuffer buff = invocation.getArgument(0);
            byte[] bytes = new byte[buff.limit()];
            buff.get(bytes);
            written.write(bytes);
            return null;
        }
    }).when(outChannel).write(any(ByteBuffer.class));

    MapMessageConverter outConverter = new MapMessageConverter();
    outConverter.setHeaderNames("bar");
    MessageConvertingTcpMessageMapper outMapper = new MessageConvertingTcpMessageMapper(outConverter);
    outboundConnection.setMapper(outMapper);
    outboundConnection.setSerializer(new MapJsonSerializer());

    Message<String> message = MessageBuilder.withPayload("foo").setHeader("bar", "baz").build();
    outboundConnection.send(message);

    final AtomicReference<Message<?>> inboundMessage = new AtomicReference<Message<?>>();
    final CountDownLatch latch = new CountDownLatch(1);
    TcpListener listener = new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            inboundMessage.set(message);
            latch.countDown();
            return false;
        }
    };
    inboundConnection.registerListener(listener);
    inboundConnection.readPacket();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertNotNull(inboundMessage.get());
    assertEquals("foo", inboundMessage.get().getPayload());
    assertEquals("baz", inboundMessage.get().getHeaders().get("bar"));
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testByteArrayReadWithBadArgs() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    byte[] out = new byte[5];
    try {/*from   w ww  . j a va 2s  . c o m*/
        stream.read(out, 1, 5);
        fail("Expected IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        stream.read(null, 1, 5);
        fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    assertEquals(0, stream.read(out, 0, 0));
    assertEquals(3, stream.read(out));
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

private void startClient(int n, SocketAddress serverAddress, final int clientIntervalMs, final int payloadSize)
        throws IOException, ExecutionException, InterruptedException, TimeoutException {
    SocketChannel toServer = SocketChannel.open();
    toServer.socket().setKeepAlive(true);
    toServer.socket().setTcpNoDelay(true);
    toServer.configureBlocking(true);/*from  w  w w  . java2s. co m*/
    toServer.connect(serverAddress);
    HashMap<String, String> headers = new HashMap<String, String>();
    String clientName = runtimeMXBean.getName() + "-client-" + n;
    headers.put(JnlpConnectionState.CLIENT_NAME_KEY, clientName);
    headers.put(JnlpConnectionState.SECRET_KEY, secretFor(clientName));
    final Channel clientChannel = handler.connect(toServer.socket(), headers, clientListener).get(15,
            TimeUnit.SECONDS);
    timer[n % timer.length].scheduleAtFixedRate(new TimerTask() {
        long start = System.currentTimeMillis();
        int index = 0;
        int times = 0;
        private NoOpCallable callable = new NoOpCallable(payloadSize == -1 ? null : new byte[payloadSize]);

        @Override
        public void run() {
            try {
                long start = System.currentTimeMillis();
                clientChannel.call(callable);
                if (config.client != null) {
                    NoOpCallable.noops.incrementAndGet();
                }
                times++;
                if (times % 1000 == 0) {
                    System.out
                            .println(String.format("  %s has run %d No-op callables. Rate %.1f/s expect %.1f/s",
                                    clientChannel.getName(), times,
                                    times * 1000.0 / (System.currentTimeMillis() - this.start),
                                    1000.0 / clientIntervalMs));
                }
                long duration = System.currentTimeMillis() - start;
                if (duration > 250L) {
                    System.err.println(String.format("  %s took %dms to complete a callable",
                            clientChannel.getName(), duration));
                }
                if (callable.payload != null && callable.payload.length > 0) {
                    // mutate the payload to prevent compression
                    int count = callable.payload.length;
                    if (count > 100) {
                        count = 100;
                    }
                    for (int j = 0; j < count; j++) {
                        callable.payload[index] = (byte) (callable.payload[index] * 31 + times);
                        index = Math.abs(index + 1) % callable.payload.length;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
                IOUtils.closeQuietly(clientChannel);
                cancel();
                System.exit(2);
            }
        }
    }, entropy.nextInt(clientIntervalMs), clientIntervalMs);
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testByteArrayBlocksForZeroRead() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    final TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    final CountDownLatch latch = new CountDownLatch(1);
    final byte[] out = new byte[4];
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(new Runnable() {

        @Override//from   w  ww . ja va2s .  c o  m
        public void run() {
            try {
                stream.read(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    });
    Thread.sleep(1000);
    assertEquals(0x00, out[0]);
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertEquals("foo\u0000", new String(out));
}

From source file:org.apache.hadoop.mapred.buffer.net.BufferExchangeSink.java

/** Open the sink for incoming connections. */
public void open() {
    /* Create a new thread for accepting new connections. */
    this.acceptor = new Thread() {
        public void run() {
            try {
                while (server.isOpen()) {
                    LOG.info("in server open");
                    SocketChannel channel = server.accept();
                    channel.configureBlocking(true);
                    /* Note: no buffered input stream due to memory pressure. */
                    DataInputStream istream = new DataInputStream(channel.socket().getInputStream());
                    DataOutputStream ostream = new DataOutputStream(
                            new BufferedOutputStream(channel.socket().getOutputStream()));

                    LOG.info("server is open");
                    if (complete()) {
                        WritableUtils.writeEnum(ostream, Connect.BUFFER_COMPLETE);
                        ostream.close();
                    } else if (handlers.size() > maxConnections) {
                        LOG.info("Connections full. connections = " + handlers.size() + ", max allowed "
                                + maxConnections);
                        WritableUtils.writeEnum(ostream, Connect.CONNECTIONS_FULL);
                        ostream.close();
                    } else {
                        WritableUtils.writeEnum(ostream, Connect.OPEN);
                        ostream.flush();

                        BufferExchange.BufferType type = WritableUtils.readEnum(istream,
                                BufferExchange.BufferType.class);
                        Handler handler = null;
                        if (BufferType.FILE == type) {
                            handler = new FileHandler(collector, istream, ostream);
                        } else if (BufferType.SNAPSHOT == type) {
                            handler = new SnapshotHandler(collector, istream, ostream);
                        } else if (BufferType.STREAM == type) {
                            handler = new StreamHandler(collector, istream, ostream);
                        } else if (BufferType.ITERATE == type) {
                            handler = new IterateHandler(collector, istream, ostream);
                        } else {
                            LOG.error("Unknown buffer type " + type);
                            channel.close();
                            continue;
                        }/* w  w w  . j  a  v a 2 s  .  c o  m*/

                        LOG.info("JBufferSink: " + ownerid + " opening connection.");
                        handlers.add(handler);
                        executor.execute(handler);
                    }
                }
                LOG.info("JBufferSink " + ownerid + " buffer response server closed.");
            } catch (IOException e) {
                if (!complete()) {
                    e.printStackTrace();
                }
            }
        }
    };
    acceptor.setDaemon(true);
    acceptor.setPriority(Thread.MAX_PRIORITY);
    acceptor.start();
}

From source file:Proxy.java

String toString(SocketChannel ch) {
    StringBuilder sb = new StringBuilder();
    Socket sock;/*from w  ww .j ava2 s .c o  m*/

    if (ch == null)
        return null;
    if ((sock = ch.socket()) == null)
        return null;
    sb.append(sock.getInetAddress().getHostName()).append(':').append(sock.getPort());
    return sb.toString();
}

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();//w  w w .  j ava  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:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testInsufficientThreads() throws Exception {
    final ExecutorService exec = Executors.newFixedThreadPool(2);
    Future<Object> future = exec.submit(() -> {
        SocketChannel channel = mock(SocketChannel.class);
        Socket socket = mock(Socket.class);
        Mockito.when(channel.socket()).thenReturn(socket);
        doAnswer(invocation -> {/*from  ww w.j a v a 2 s  .com*/
            ByteBuffer buffer = invocation.getArgument(0);
            buffer.position(1);
            return 1;
        }).when(channel).read(Mockito.any(ByteBuffer.class));
        when(socket.getReceiveBufferSize()).thenReturn(1024);
        final TcpNioConnection connection = new TcpNioConnection(channel, false, false, nullPublisher, null);
        connection.setTaskExecutor(exec);
        connection.setPipeTimeout(200);
        Method method = TcpNioConnection.class.getDeclaredMethod("doRead");
        method.setAccessible(true);
        // Nobody reading, should timeout on 6th write.
        try {
            for (int i = 0; i < 6; i++) {
                method.invoke(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw (Exception) e.getCause();
        }
        return null;
    });
    try {
        Object o = future.get(10, TimeUnit.SECONDS);
        fail("Expected exception, got " + o);
    } catch (ExecutionException e) {
        assertEquals("Timed out waiting for buffer space", e.getCause().getMessage());
    }
}