Search in sources :

Example 61 with SocketChannel

use of java.nio.channels.SocketChannel in project canal by alibaba.

the class CanalServerWithNettyTest method testAuth.

@Test
public void testAuth() {
    try {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress("127.0.0.1", 1088));
        Packet p = Packet.parseFrom(readNextPacket(channel));
        if (p.getVersion() != 1) {
            throw new Exception("unsupported version at this client.");
        }
        if (p.getType() != PacketType.HANDSHAKE) {
            throw new Exception("expect handshake but found other type.");
        }
        //
        Handshake handshake = Handshake.parseFrom(p.getBody());
        System.out.println(handshake.getSupportedCompressionsList());
        //
        ClientAuth ca = ClientAuth.newBuilder().setUsername("").setNetReadTimeout(10000).setNetWriteTimeout(10000).build();
        writeWithHeader(channel, Packet.newBuilder().setType(PacketType.CLIENTAUTHENTICATION).setBody(ca.toByteString()).build().toByteArray());
        //
        p = Packet.parseFrom(readNextPacket(channel));
        if (p.getType() != PacketType.ACK) {
            throw new Exception("unexpected packet type when ack is expected");
        }
        Ack ack = Ack.parseFrom(p.getBody());
        if (ack.getErrorCode() > 0) {
            throw new Exception("something goes wrong when doing authentication: " + ack.getErrorMessage());
        }
        writeWithHeader(channel, Packet.newBuilder().setType(PacketType.SUBSCRIPTION).setBody(Sub.newBuilder().setDestination(DESTINATION).setClientId("1").build().toByteString()).build().toByteArray());
        //
        p = Packet.parseFrom(readNextPacket(channel));
        ack = Ack.parseFrom(p.getBody());
        if (ack.getErrorCode() > 0) {
            throw new Exception("failed to subscribe with reason: " + ack.getErrorMessage());
        }
        for (int i = 0; i < 10; i++) {
            writeWithHeader(channel, Packet.newBuilder().setType(PacketType.GET).setBody(Get.newBuilder().setDestination(DESTINATION).setClientId("1").setFetchSize(10).build().toByteString()).build().toByteArray());
            p = Packet.parseFrom(readNextPacket(channel));
            long batchId = -1L;
            switch(p.getType()) {
                case MESSAGES:
                    {
                        Messages messages = Messages.parseFrom(p.getBody());
                        batchId = messages.getBatchId();
                        break;
                    }
                case ACK:
                    {
                        ack = Ack.parseFrom(p.getBody());
                        if (ack.getErrorCode() > 0) {
                            throw new Exception("failed to subscribe with reason: " + ack.getErrorMessage());
                        }
                        break;
                    }
                default:
                    {
                        throw new Exception("unexpected packet type: " + p.getType());
                    }
            }
            System.out.println("!!!!!!!!!!!!!!!!! " + batchId);
            Thread.sleep(1000L);
            writeWithHeader(channel, Packet.newBuilder().setType(PacketType.CLIENTACK).setBody(ClientAck.newBuilder().setDestination(DESTINATION).setClientId("1").setBatchId(batchId).build().toByteString()).build().toByteArray());
        }
        writeWithHeader(channel, Packet.newBuilder().setType(PacketType.CLIENTROLLBACK).setBody(ClientRollback.newBuilder().setDestination(DESTINATION).setClientId("1").build().toByteString()).build().toByteArray());
        writeWithHeader(channel, Packet.newBuilder().setType(PacketType.UNSUBSCRIPTION).setBody(Unsub.newBuilder().setDestination(DESTINATION).setClientId("1").build().toByteString()).build().toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) Packet(com.alibaba.otter.canal.protocol.CanalPacket.Packet) Messages(com.alibaba.otter.canal.protocol.CanalPacket.Messages) InetSocketAddress(java.net.InetSocketAddress) Ack(com.alibaba.otter.canal.protocol.CanalPacket.Ack) ClientAck(com.alibaba.otter.canal.protocol.CanalPacket.ClientAck) ClientAuth(com.alibaba.otter.canal.protocol.CanalPacket.ClientAuth) IOException(java.io.IOException) Handshake(com.alibaba.otter.canal.protocol.CanalPacket.Handshake) Test(org.junit.Test)

Example 62 with SocketChannel

use of java.nio.channels.SocketChannel in project wildfly by wildfly.

the class SocketFactoryBase method createSocket.

public Socket createSocket(String type, InetSocketAddress inetSocketAddress) throws IOException {
    SocketChannel socketChannel = null;
    Socket socket = null;
    if (orb.getORBData().connectionSocketType().equals(ORBConstants.SOCKETCHANNEL)) {
        socketChannel = SocketChannel.open(inetSocketAddress);
        socket = socketChannel.socket();
    } else {
        socket = new Socket(inetSocketAddress.getHostName(), inetSocketAddress.getPort());
    }
    // Disable Nagle's algorithm (i.e., always send immediately).
    socket.setTcpNoDelay(true);
    return socket;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket)

Example 63 with SocketChannel

use of java.nio.channels.SocketChannel in project heron by twitter.

the class ConnectTest method testStart.

/**
   * Test connection
   */
@Test
public void testStart() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(HOST, serverPort));
    SocketChannel socketChannel = null;
    try {
        runStreamManagerClient();
        socketChannel = serverSocketChannel.accept();
        configure(socketChannel);
        socketChannel.configureBlocking(false);
        close(serverSocketChannel);
        // Receive request
        IncomingPacket incomingPacket = new IncomingPacket();
        while (incomingPacket.readFromChannel(socketChannel) != 0) {
            // 1ms sleep to mitigate busy looping
            SysUtils.sleep(1);
        }
        // Send back response
        // Though we do not use typeName, we need to unpack it first,
        // since the order is required
        String typeName = incomingPacket.unpackString();
        REQID rid = incomingPacket.unpackREQID();
        OutgoingPacket outgoingPacket = new OutgoingPacket(rid, UnitTestHelper.getRegisterInstanceResponse());
        outgoingPacket.writeToChannel(socketChannel);
        for (int i = 0; i < Constants.RETRY_TIMES; i++) {
            InstanceControlMsg instanceControlMsg = inControlQueue.poll();
            if (instanceControlMsg != null) {
                nioLooper.exitLoop();
                threadsPool.shutdownNow();
                PhysicalPlanHelper physicalPlanHelper = instanceControlMsg.getNewPhysicalPlanHelper();
                Assert.assertEquals("test-bolt", physicalPlanHelper.getMyComponent());
                Assert.assertEquals(InetAddress.getLocalHost().getHostName(), physicalPlanHelper.getMyHostname());
                Assert.assertEquals(0, physicalPlanHelper.getMyInstanceIndex());
                Assert.assertEquals(1, physicalPlanHelper.getMyTaskId());
                break;
            } else {
                SysUtils.sleep(Constants.RETRY_INTERVAL_MS);
            }
        }
    } catch (ClosedChannelException ignored) {
    } finally {
        close(socketChannel);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) IncomingPacket(com.twitter.heron.common.network.IncomingPacket) InstanceControlMsg(com.twitter.heron.instance.InstanceControlMsg) PhysicalPlanHelper(com.twitter.heron.common.utils.misc.PhysicalPlanHelper) InetSocketAddress(java.net.InetSocketAddress) REQID(com.twitter.heron.common.network.REQID) ServerSocketChannel(java.nio.channels.ServerSocketChannel) OutgoingPacket(com.twitter.heron.common.network.OutgoingPacket) Test(org.junit.Test)

Example 64 with SocketChannel

use of java.nio.channels.SocketChannel in project heron by twitter.

the class HeronServer method handleAccept.

@Override
public void handleAccept(SelectableChannel channel) {
    try {
        SocketChannel socketChannel = acceptChannel.accept();
        if (socketChannel != null) {
            socketChannel.configureBlocking(false);
            // Set the maximum possible send and receive buffers
            socketChannel.socket().setSendBufferSize(socketOptions.getSocketSendBufferSizeInBytes());
            socketChannel.socket().setReceiveBufferSize(socketOptions.getSocketReceivedBufferSizeInBytes());
            socketChannel.socket().setTcpNoDelay(true);
            SocketChannelHelper helper = new SocketChannelHelper(nioLooper, this, socketChannel, socketOptions);
            activeConnections.put(socketChannel, helper);
            onConnect(socketChannel);
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Error while accepting a new connection ", e);
    // Note:- we are not calling onError
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) IOException(java.io.IOException)

Example 65 with SocketChannel

use of java.nio.channels.SocketChannel in project heron by twitter.

the class HeronServerTest method testClose.

/**
   * Method: stop()
   */
@Test
public void testClose() throws Exception {
    runBase();
    heronServer.stop();
    Map<SocketChannel, SocketChannelHelper> activeConnections = heronServer.getActiveConnections();
    ServerSocketChannel acceptChannel = heronServer.getAcceptChannel();
    Assert.assertNotNull(acceptChannel);
    Assert.assertTrue(!acceptChannel.isOpen());
    Assert.assertNotNull(activeConnections);
    Assert.assertEquals(0, activeConnections.size());
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Test(org.junit.Test)

Aggregations

SocketChannel (java.nio.channels.SocketChannel)662 IOException (java.io.IOException)298 ServerSocketChannel (java.nio.channels.ServerSocketChannel)285 InetSocketAddress (java.net.InetSocketAddress)202 ByteBuffer (java.nio.ByteBuffer)163 SelectionKey (java.nio.channels.SelectionKey)105 Socket (java.net.Socket)87 Test (org.junit.Test)81 ClosedChannelException (java.nio.channels.ClosedChannelException)50 Selector (java.nio.channels.Selector)42 SocketAddress (java.net.SocketAddress)35 ServerSocket (java.net.ServerSocket)31 ClosedSelectorException (java.nio.channels.ClosedSelectorException)28 CancelledKeyException (java.nio.channels.CancelledKeyException)27 ConnectException (java.net.ConnectException)26 ArrayList (java.util.ArrayList)26 SocketTimeoutException (java.net.SocketTimeoutException)23 SelectableChannel (java.nio.channels.SelectableChannel)21 SocketException (java.net.SocketException)20 HashMap (java.util.HashMap)20