Example usage for io.vertx.core.net NetSocket handler

List of usage examples for io.vertx.core.net NetSocket handler

Introduction

In this page you can find the example usage for io.vertx.core.net NetSocket handler.

Prototype

@Override
    NetSocket handler(Handler<Buffer> handler);

Source Link

Usage

From source file:com.groupon.vertx.memcache.stream.MemcacheSocket.java

License:Apache License

public MemcacheSocket(final NetSocket socket, ConcurrentLinkedQueue<MemcacheCommand> pendingCommands) {
    this.socket = socket;
    this.output = new MemcacheOutputStream(socket);
    this.pendingCommands = pendingCommands;
    this.input = new MemcacheInputStream(pendingCommands);

    socket.handler(buffer -> {
        try {//from w ww . j av  a  2  s  . co  m
            input.processBuffer(buffer);
        } catch (Exception ex) {
            // Error processing the commands so close the socket.
            socket.close();
        }
    });
}

From source file:com.groupon.vertx.redis.RedisSocket.java

License:Apache License

public RedisSocket(final NetSocket socket) {
    this.socket = socket;
    this.output = new RedisOutputStream(socket);
    this.pendingCommands = new ConcurrentLinkedQueue<>();
    this.input = new RedisInputStream(pendingCommands);

    socket.handler(new Handler<Buffer>() {
        public void handle(Buffer buff) {
            try {
                log.trace("handle", "beforeProcessBuffer");
                input.processBuffer(buff);
            } catch (Exception ex) {
                log.error("handle", "exception", "unknown", ex);
                // Error processing the commands so close the socket.
                socket.close();/*from   ww w. j  a  va2  s. c  o  m*/
            }
        }
    });
}

From source file:com.sibvisions.rad.remote.vertx.NetSocketConnection.java

License:Apache License

/**
 * {@inheritDoc}// www  .  j a  v  a 2 s  .  c  o  m
 */
@Override
public void open(ConnectionInfo pConnectionInfo) throws Throwable {
    closeSocket();

    NetClientOptions options = new NetClientOptions();
    options.setReconnectAttempts(3);
    options.setConnectTimeout(5000);
    options.setReconnectInterval(1000);

    client = vertx.createNetClient(options);
    client.connect(iPort, sHost, new Handler<AsyncResult<NetSocket>>() {
        public void handle(final AsyncResult<NetSocket> pCommunication) {
            NetSocket sock = pCommunication.result();

            if (sock != null) {
                sock.handler(new Handler<Buffer>() {
                    public void handle(Buffer pBuffer) {
                        if (inputStream != null) {
                            inputStream.receive(pBuffer);
                        }
                    }
                });

                sock.exceptionHandler(new Handler<Throwable>() {
                    public void handle(Throwable pException) {
                        if (inputStream != null) {
                            inputStream.finish();
                        }
                    }
                });

                sock.endHandler(new Handler<Void>() {
                    public void handle(Void pParam) {
                        if (inputStream != null) {
                            inputStream.finish();
                        }
                    }
                });
            }

            synchronized (NetSocketConnection.this) {
                if (pCommunication.succeeded()) {
                    socket = sock;
                } else {
                    LoggerFactory.getInstance(NetSocketConnection.class).error(pCommunication.cause());

                    socket = null;
                }

                NetSocketConnection.this.notify();
            }
        }
    });

    synchronized (this) {
        if (socket == null) {
            wait(15000);
        }
    }

    if (socket == null) {
        throw new ConnectException("Can't establish connection!");
    }

    socket.write(Buffer.buffer(new byte[] { STREAM_COMMUNICATION }));

    super.open(pConnectionInfo);

    if (oInitialConId == null) {
        oInitialConId = pConnectionInfo.getConnectionId();
    }
}

From source file:com.sibvisions.rad.remote.vertx.NetSocketConnection.java

License:Apache License

/**
 * Opens a new transfer client.//from  w  w  w  .  j  a  va  2 s.  c  o  m
 * 
 * @throws IOException if opening failed
 */
private void openTransfer() throws IOException {
    closeTransfer();

    if (socketTransfer != null) {
        socketTransfer.close();
        socketTransfer = null;
    }

    NetClientOptions options = new NetClientOptions();
    options.setReconnectAttempts(3);
    options.setReconnectInterval(1000);

    clientTransfer = vertx.createNetClient(options);

    isTransfer = new SyncedInputStream();

    clientTransfer.connect(iPort, sHost, new Handler<AsyncResult<NetSocket>>() {
        public void handle(AsyncResult<NetSocket> pCommunication) {
            NetSocket sock = pCommunication.result();

            if (sock != null) {
                sock.handler(new Handler<Buffer>() {
                    public void handle(Buffer pBuffer) {
                        if (isTransfer != null) {
                            isTransfer.receive(pBuffer);
                        }
                    }
                });

                sock.exceptionHandler(new Handler<Throwable>() {
                    public void handle(Throwable pException) {
                        if (isTransfer != null) {
                            isTransfer.finish();
                        }
                    }
                });

                sock.endHandler(new Handler<Void>() {
                    public void handle(Void pParam) {
                        if (isTransfer != null) {
                            isTransfer.finish();
                        }
                    }

                });
            }

            synchronized (clientTransfer) {
                socketTransfer = sock;

                clientTransfer.notify();
            }
        }
    });

    try {
        synchronized (clientTransfer) {
            if (socketTransfer == null) {
                clientTransfer.wait(15000);
            }
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie);
    }

    if (socketTransfer == null) {
        throw new ConnectException("Can't establish transfer connection!");
    }
}

From source file:com.sibvisions.vertx.NetSocketServer.java

License:Apache License

/**
 * Starts the server to listen on the configured port.
 *//*from  w w  w . j  a v  a 2 s  . c  o  m*/
public void start() {
    if (vertx == null) {
        vertx = Vertx.vertx();
    }

    NetServerOptions options = new NetServerOptions();
    options.setTcpKeepAlive(true);
    options.setTcpNoDelay(true);

    srvVertx = vertx.createNetServer(options);

    srvVertx.connectHandler(new Handler<NetSocket>() {
        public void handle(NetSocket pSocket) {
            AbstractDataHandler dataHandler = new NetDataHandler(srvJVx, pSocket);

            pSocket.handler(dataHandler);
            pSocket.endHandler(new StopHandler(dataHandler));
            pSocket.exceptionHandler(new ExceptionHandler(dataHandler));
        }
    });

    srvVertx.listen(iPort, sInterface);
}

From source file:io.servicecomb.foundation.vertx.client.tcp.TcpClientConnection.java

License:Apache License

private void onConnectSuccess(NetSocket socket) {
    LOGGER.info("connectd to address {} success in thread {}.", socketAddress.toString(),
            Thread.currentThread().getName());
    // currently, socket always be NetSocketImpl
    this.initNetSocket((NetSocketImpl) socket);
    socket.handler(new TcpParser(this::onReply));

    socket.exceptionHandler(this::onException);
    socket.closeHandler(this::onClosed);

    // //from w ww. j a v a2 s.co m
    tryLogin();
}

From source file:io.servicecomb.foundation.vertx.server.TcpServerConnection.java

License:Apache License

public void init(NetSocket netSocket) {
    // currently, socket always be NetSocketImpl
    this.initNetSocket((NetSocketImpl) netSocket);

    String remoteAddress = netSocket.remoteAddress().toString();
    LOGGER.info("connect from {}, in thread {}", remoteAddress, Thread.currentThread().getName());
    netSocket.exceptionHandler(e -> {
        LOGGER.error("disconected from {}, in thread {}, cause {}", remoteAddress,
                Thread.currentThread().getName(), e.getMessage());
    });/* ww  w . j  a v a  2  s .com*/
    netSocket.closeHandler(Void -> {
        LOGGER.error("disconected from {}, in thread {}", remoteAddress, Thread.currentThread().getName());
    });

    netSocket.handler(splitter);
}

From source file:org.apache.servicecomb.foundation.vertx.client.tcp.TcpClientConnection.java

License:Apache License

private void onConnectSuccess(NetSocket socket) {
    LOGGER.info("connected to address {} success in thread {}.", socketAddress.toString(),
            Thread.currentThread().getName());
    // currently, socket always be NetSocketImpl
    this.initNetSocket((NetSocketImpl) socket);
    socket.handler(new TcpParser(this::onReply));

    socket.exceptionHandler(this::onException);
    socket.closeHandler(this::onClosed);

    // /*from  w w w  .java 2  s  .c o  m*/
    tryLogin();
}

From source file:org.apache.servicecomb.foundation.vertx.server.TcpServerConnection.java

License:Apache License

public void init(NetSocket netSocket, AtomicInteger connectedCounter) {
    // currently, socket always be NetSocketImpl
    this.initNetSocket((NetSocketImpl) netSocket);

    String remoteAddress = netSocket.remoteAddress().toString();
    LOGGER.info("connect from {}, in thread {}", remoteAddress, Thread.currentThread().getName());
    netSocket.exceptionHandler(e -> {
        LOGGER.error("disconected from {}, in thread {}, cause {}", remoteAddress,
                Thread.currentThread().getName(), e.getMessage());
    });// www .ja va  2s .c om
    netSocket.closeHandler(Void -> {
        LOGGER.error("disconected from {}, in thread {}", remoteAddress, Thread.currentThread().getName());

        int connectedCount = connectedCounter.decrementAndGet();
        EventManager.post(
                new ClientEvent(remoteAddress, ConnectionEvent.Closed, TransportType.Highway, connectedCount));
    });

    netSocket.handler(splitter);
}

From source file:org.lealone.client.ClientSession.java

License:Mozilla Public License

private Transfer initTransfer(ConnectionInfo ci, String server) throws Exception {
    int port = Constants.DEFAULT_TCP_PORT;
    // IPv6: RFC 2732 format is '[a:b:c:d:e:f:g:h]' or
    // '[a:b:c:d:e:f:g:h]:port'
    // RFC 2396 format is 'a.b.c.d' or 'a.b.c.d:port' or 'hostname' or
    // 'hostname:port'
    int startIndex = server.startsWith("[") ? server.indexOf(']') : 0;
    int idx = server.indexOf(':', startIndex);
    if (idx >= 0) {
        port = Integer.decode(server.substring(idx + 1));
        server = server.substring(0, idx);
    }/*from  w  ww  .  j  av a2  s  .c om*/

    final String hostAndPort = server + ":" + port;

    asyncConnection = asyncConnections.get(hostAndPort);
    if (asyncConnection == null) {
        synchronized (ClientSession.class) {
            asyncConnection = asyncConnections.get(hostAndPort);
            if (asyncConnection == null) {
                CountDownLatch latch = new CountDownLatch(1);
                client.connect(port, server, res -> {
                    if (res.succeeded()) {
                        NetSocket socket = res.result();
                        asyncConnection = new AsyncConnection(socket, false);
                        asyncConnections.put(hostAndPort, asyncConnection);
                        socket.handler(asyncConnection);
                        latch.countDown();
                    } else {
                        throw DbException.convert(res.cause());
                    }
                });
                latch.await();
            }
        }
    }
    sessionId = getNextId();
    transfer = asyncConnection.createTransfer(this);
    asyncConnection.writeInitPacket(this, sessionId, transfer, ci);
    asyncConnection.addSession(sessionId, this);
    return transfer;
}