Search in sources :

Example 1 with NetSocketInternal

use of io.vertx.core.net.impl.NetSocketInternal in project vert.x by eclipse.

the class WebSocketTest method testServerCloseHandshake.

@Test
public void testServerCloseHandshake() {
    short status = (short) (4000 + TestUtils.randomPositiveInt() % 100);
    waitFor(2);
    server = vertx.createHttpServer();
    server.webSocketHandler(ws -> {
        ws.closeHandler(sc -> {
            assertEquals((Short) (short) status, ws.closeStatusCode());
            complete();
        });
    });
    server.listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, onSuccess(v1 -> {
        client = vertx.createHttpClient();
        handshake(client, req -> {
            req.send(onSuccess(resp -> {
                assertEquals(101, resp.statusCode());
                Http1xClientConnection conn = (Http1xClientConnection) req.connection();
                NetSocketInternal soi = conn.toNetSocket();
                soi.channelHandlerContext().pipeline().addBefore("handler", "encoder", new WebSocket13FrameEncoder(true));
                soi.channelHandlerContext().pipeline().addBefore("handler", "decoder", new WebSocket13FrameDecoder(false, false, 1000));
                String reason = randomAlphaString(10);
                soi.writeMessage(new CloseWebSocketFrame(status, reason));
                AtomicBoolean closeFrameReceived = new AtomicBoolean();
                soi.messageHandler(msg -> {
                    try {
                        if (msg instanceof CloseWebSocketFrame) {
                            CloseWebSocketFrame frame = (CloseWebSocketFrame) msg;
                            assertEquals(status, frame.statusCode());
                            assertEquals(reason, frame.reasonText());
                            closeFrameReceived.set(true);
                        }
                    } finally {
                        ReferenceCountUtil.release(msg);
                    }
                });
                soi.closeHandler(v2 -> {
                    assertTrue(closeFrameReceived.get());
                    complete();
                });
            }));
        });
    }));
    await();
}
Also used : WebSocketInternal(io.vertx.core.http.impl.WebSocketInternal) MultiMap(io.vertx.core.MultiMap) Context(io.vertx.core.Context) Matcher(java.util.regex.Matcher) PlatformDependent(io.netty.util.internal.PlatformDependent) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT_HTTP_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_HOST) ReadStream(io.vertx.core.streams.ReadStream) HAProxy(io.vertx.test.proxy.HAProxy) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) CheckingSender(io.vertx.test.core.CheckingSender) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) Trust(io.vertx.test.tls.Trust) BlockingQueue(java.util.concurrent.BlockingQueue) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Certificate(java.security.cert.Certificate) Buffer(io.vertx.core.buffer.Buffer) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Cert(io.vertx.test.tls.Cert) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) NetSocket(io.vertx.core.net.NetSocket) java.util(java.util) MessageDigest(java.security.MessageDigest) DEFAULT_HTTP_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_PORT) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) DEFAULT_HTTPS_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_HOST) BiConsumer(java.util.function.BiConsumer) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocket13FrameDecoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) DEFAULT_TEST_URI(io.vertx.core.http.HttpTestBase.DEFAULT_TEST_URI) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) Promise(io.vertx.core.Promise) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) IOException(java.io.IOException) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WebSocket13FrameEncoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) DEFAULT_HTTPS_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_PORT) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) Http1xClientConnection(io.vertx.core.http.impl.Http1xClientConnection) WebSocket13FrameEncoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Http1xClientConnection(io.vertx.core.http.impl.Http1xClientConnection) WebSocket13FrameDecoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) Test(org.junit.Test)

Example 2 with NetSocketInternal

use of io.vertx.core.net.impl.NetSocketInternal in project vert.x by eclipse.

the class Http1xClientConnection method toNetSocket.

/**
 * @return a raw {@code NetSocket} - for internal use
 */
public NetSocketInternal toNetSocket() {
    removeChannelHandlers();
    NetSocketImpl socket = new NetSocketImpl(context, chctx, null, metrics());
    socket.metric(metric());
    evictionHandler.handle(null);
    chctx.pipeline().replace("handler", "handler", VertxHandler.create(ctx -> socket));
    return socket;
}
Also used : NetSocketImpl(io.vertx.core.net.impl.NetSocketImpl) java.util(java.util) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) InboundBuffer(io.vertx.core.streams.impl.InboundBuffer) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) io.vertx.core(io.vertx.core) ContextInternal(io.vertx.core.impl.ContextInternal) HttpClientMetrics(io.vertx.core.spi.metrics.HttpClientMetrics) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Unpooled(io.netty.buffer.Unpooled) WebSocketClientExtensionHandshaker(io.netty.handler.codec.http.websocketx.extensions.WebSocketClientExtensionHandshaker) ByteBuf(io.netty.buffer.ByteBuf) HttpVersion(io.vertx.core.http.HttpVersion) SpanKind(io.vertx.core.spi.tracing.SpanKind) WriteStream(io.vertx.core.streams.WriteStream) BiConsumer(java.util.function.BiConsumer) io.netty.channel(io.netty.channel) URI(java.net.URI) ZlibCodecFactory(io.netty.handler.codec.compression.ZlibCodecFactory) V13(io.netty.handler.codec.http.websocketx.WebSocketVersion.V13) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) VertxHandler(io.vertx.core.net.impl.VertxHandler) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) FutureListener(io.netty.util.concurrent.FutureListener) PerMessageDeflateServerExtensionHandshaker(io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateServerExtensionHandshaker) TagExtractor(io.vertx.core.spi.tracing.TagExtractor) VertxTracer(io.vertx.core.spi.tracing.VertxTracer) HttpHeaders(io.vertx.core.http.HttpHeaders) io.vertx.core.http(io.vertx.core.http) HeadersAdaptor(io.vertx.core.http.impl.headers.HeadersAdaptor) DecoderResult(io.netty.handler.codec.DecoderResult) io.netty.handler.codec.http(io.netty.handler.codec.http) WebSocketClientExtensionHandler(io.netty.handler.codec.http.websocketx.extensions.WebSocketClientExtensionHandler) Buffer(io.vertx.core.buffer.Buffer) V08(io.netty.handler.codec.http.websocketx.WebSocketVersion.V08) io.netty.handler.codec.http.websocketx(io.netty.handler.codec.http.websocketx) PerMessageDeflateClientExtensionHandshaker(io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateClientExtensionHandshaker) HttpMethod(io.vertx.core.http.HttpMethod) DeflateFrameClientExtensionHandshaker(io.netty.handler.codec.http.websocketx.extensions.compression.DeflateFrameClientExtensionHandshaker) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) ClientMetrics(io.vertx.core.spi.metrics.ClientMetrics) V07(io.netty.handler.codec.http.websocketx.WebSocketVersion.V07) V00(io.netty.handler.codec.http.websocketx.WebSocketVersion.V00) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) NetSocketImpl(io.vertx.core.net.impl.NetSocketImpl)

Example 3 with NetSocketInternal

use of io.vertx.core.net.impl.NetSocketInternal in project vertx-proton by vert-x3.

the class ProtonTransport method flush.

void flush() {
    boolean done = false;
    while (!done) {
        ByteBuffer outputBuffer = transport.getOutputBuffer();
        if (outputBuffer != null && outputBuffer.hasRemaining()) {
            final NetSocketInternal internal = (NetSocketInternal) socket;
            final ByteBuf bb = internal.channelHandlerContext().alloc().directBuffer(outputBuffer.remaining());
            bb.writeBytes(outputBuffer);
            internal.writeMessage(bb);
            transport.outputConsumed();
        } else {
            done = true;
        }
    }
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal)

Example 4 with NetSocketInternal

use of io.vertx.core.net.impl.NetSocketInternal in project hono by eclipse.

the class CommandAndControlMqttIT method injectMqttClientPubAckBlocker.

private Future<Void> injectMqttClientPubAckBlocker(final AtomicBoolean outboundPubAckBlocked) {
    // Therefore the underlying NetSocket pipeline is used here to filter out the outbound PubAck messages.
    try {
        final Method connectionMethod = MqttClientImpl.class.getDeclaredMethod("connection");
        connectionMethod.setAccessible(true);
        final NetSocketInternal connection = (NetSocketInternal) connectionMethod.invoke(mqttClient);
        connection.channelHandlerContext().pipeline().addBefore("handler", "OutboundPubAckBlocker", new ChannelOutboundHandlerAdapter() {

            @Override
            public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
                if (outboundPubAckBlocked.get() && msg instanceof io.netty.handler.codec.mqtt.MqttPubAckMessage) {
                    LOGGER.debug("suppressing PubAck, message id: {}", ((MqttPubAckMessage) msg).variableHeader().messageId());
                } else {
                    super.write(ctx, msg, promise);
                }
            }
        });
        return Future.succeededFuture();
    } catch (final Exception e) {
        LOGGER.error("failed to inject PubAck blocking handler");
        return Future.failedFuture(new Exception("failed to inject PubAck blocking handler", e));
    }
}
Also used : MqttPubAckMessage(io.netty.handler.codec.mqtt.MqttPubAckMessage) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) Method(java.lang.reflect.Method) IllegalStateException(javax.jms.IllegalStateException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal)

Example 5 with NetSocketInternal

use of io.vertx.core.net.impl.NetSocketInternal in project vert.x by eclipse.

the class NetTest method testNetSocketInternalEvent.

@Test
public void testNetSocketInternalEvent() throws Exception {
    server.connectHandler(so -> {
        NetSocketInternal soi = (NetSocketInternal) so;
        Object expectedEvent = new Object();
        soi.eventHandler(event -> {
            assertSame(expectedEvent, event);
            soi.close();
        });
        ChannelPipeline pipeline = soi.channelHandlerContext().pipeline();
        pipeline.addFirst(new ChannelHandlerAdapter() {

            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                super.handlerAdded(ctx);
                ctx.executor().schedule(() -> {
                    ctx.fireUserEventTriggered(expectedEvent);
                }, 10, TimeUnit.MILLISECONDS);
            }
        });
    });
    startServer();
    client.connect(testAddress, onSuccess(so -> {
        so.closeHandler(v -> testComplete());
    }));
    await();
}
Also used : ChannelHandlerAdapter(io.netty.channel.ChannelHandlerAdapter) HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) CoreMatchers(org.hamcrest.CoreMatchers) NetServerImpl(io.vertx.core.net.impl.NetServerImpl) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) PlatformDependent(io.netty.util.internal.PlatformDependent) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReadStream(io.vertx.core.streams.ReadStream) JsonObject(io.vertx.core.json.JsonObject) CheckingSender(io.vertx.test.core.CheckingSender) Logger(io.vertx.core.impl.logging.Logger) VertxHandler(io.vertx.core.net.impl.VertxHandler) ChannelHandlerAdapter(io.netty.channel.ChannelHandlerAdapter) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) java.util.concurrent(java.util.concurrent) Message(io.vertx.core.eventbus.Message) Trust(io.vertx.test.tls.Trust) ChannelPipeline(io.netty.channel.ChannelPipeline) InetSocketAddress(java.net.InetSocketAddress) io.vertx.core.http(io.vertx.core.http) StandardCharsets(java.nio.charset.StandardCharsets) io.netty.handler.codec.http(io.netty.handler.codec.http) SSLException(javax.net.ssl.SSLException) Certificate(java.security.cert.Certificate) Buffer(io.vertx.core.buffer.Buffer) Cert(io.vertx.test.tls.Cert) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) HttpVersion(io.netty.handler.codec.http.HttpVersion) java.util(java.util) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) io.vertx.core(io.vertx.core) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLSession(javax.net.ssl.SSLSession) ByteBuf(io.netty.buffer.ByteBuf) io.vertx.test.proxy(io.vertx.test.proxy) OutputStreamWriter(java.io.OutputStreamWriter) Assume(org.junit.Assume) VertxInternal(io.vertx.core.impl.VertxInternal) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) BufferedWriter(java.io.BufferedWriter) HttpMethod(io.netty.handler.codec.http.HttpMethod) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) File(java.io.File) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) AtomicLong(java.util.concurrent.atomic.AtomicLong) Rule(org.junit.Rule) TemporaryFolder(org.junit.rules.TemporaryFolder) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) JsonObject(io.vertx.core.json.JsonObject) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPipeline(io.netty.channel.ChannelPipeline) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) Test(org.junit.Test)

Aggregations

NetSocketInternal (io.vertx.core.net.impl.NetSocketInternal)9 ByteBuf (io.netty.buffer.ByteBuf)7 Buffer (io.vertx.core.buffer.Buffer)7 Unpooled (io.netty.buffer.Unpooled)6 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 io.netty.handler.codec.http (io.netty.handler.codec.http)6 PlatformDependent (io.netty.util.internal.PlatformDependent)6 io.vertx.core (io.vertx.core)6 ChannelHandlerAdapter (io.netty.channel.ChannelHandlerAdapter)5 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)5 ChannelPipeline (io.netty.channel.ChannelPipeline)5 ConnectTimeoutException (io.netty.channel.ConnectTimeoutException)5 HttpMethod (io.netty.handler.codec.http.HttpMethod)5 HttpVersion (io.netty.handler.codec.http.HttpVersion)5 Message (io.vertx.core.eventbus.Message)5 MessageConsumer (io.vertx.core.eventbus.MessageConsumer)5 io.vertx.core.http (io.vertx.core.http)5 ConcurrentHashSet (io.vertx.core.impl.ConcurrentHashSet)5 Utils (io.vertx.core.impl.Utils)5 VertxInternal (io.vertx.core.impl.VertxInternal)5