List of usage examples for io.netty.channel SimpleChannelInboundHandler SimpleChannelInboundHandler
protected SimpleChannelInboundHandler()
From source file:io.hekate.cluster.seed.multicast.MulticastSeedNodeProvider.java
License:Apache License
private SimpleChannelInboundHandler<DatagramPacket> createListenerHandler(SeedNode thisNode, ByteBuf seedNodeInfo) {/* w w w.j a va2 s .co m*/ return new SimpleChannelInboundHandler<DatagramPacket>() { @Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf buf = msg.content(); if (buf.readableBytes() > 4 && buf.readInt() == Utils.MAGIC_BYTES) { MessageTYpe msgType = MessageTYpe.values()[buf.readByte()]; if (msgType == MessageTYpe.DISCOVERY) { String cluster = decodeUtf(buf); InetSocketAddress address = decodeAddress(buf); if (thisNode.cluster().equals(cluster) && !address.equals(thisNode.address())) { onDiscoveryMessage(address); DatagramPacket response = new DatagramPacket(seedNodeInfo.copy(), msg.sender()); ctx.writeAndFlush(response); } } } } }; }
From source file:io.jsync.dns.impl.DefaultDnsClient.java
License:Open Source License
@SuppressWarnings("unchecked") private void lookup(final Iterator<InetSocketAddress> dns, final String name, final DefaultFutureResult result, final int... types) { bootstrap.connect(dns.next()).addListener(new RetryChannelFutureListener(dns, name, result, types) { @Override//from ww w . ja v a 2s . c o m public void onSuccess(ChannelFuture future) throws Exception { DnsQuery query = new DnsQuery(ThreadLocalRandom.current().nextInt()); for (int type : types) { query.addQuestion(new DnsQuestion(name, type)); } future.channel().writeAndFlush(query) .addListener(new RetryChannelFutureListener(dns, name, result, types) { @Override public void onSuccess(ChannelFuture future) throws Exception { future.channel().pipeline().addLast(new SimpleChannelInboundHandler<DnsResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DnsResponse msg) throws Exception { DnsResponseCode code = DnsResponseCode .valueOf(msg.getHeader().getResponseCode()); if (code == DnsResponseCode.NOERROR) { List<DnsResource> resources = msg.getAnswers(); List<Object> records = new ArrayList<>(resources.size()); for (DnsResource resource : msg.getAnswers()) { Object record = RecordDecoderFactory.getFactory() .decode(resource.type(), msg, resource); records.add(record); } setResult(result, ctx.channel().eventLoop(), records); } else { setResult(result, ctx.channel().eventLoop(), new DnsException(code)); } ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { setResult(result, ctx.channel().eventLoop(), cause); ctx.close(); } }); } }); } }); }
From source file:io.netty.example.http2.helloworld.frame.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 */// w w w . j a v a 2s. com private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); pipeline.addAfter(ctx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:io.netty.example.http2.helloworld.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *///from w w w .j a va2 s . c om private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory); final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler( sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build()); p.addLast(cleartextHttp2ServerUpgradeHandler); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); pipeline.addAfter(ctx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:io.undertow.websockets.utils.WebSocketTestClient.java
License:Open Source License
/** * Send the WebSocketFrame and call the FrameListener once a frame was received as response or * when an Exception was caught.//from w ww . j a v a 2s. co m */ public WebSocketTestClient send(WebSocketFrame frame, final FrameListener listener) { ch.pipeline().addLast("responseHandler" + count.incrementAndGet(), new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof CloseWebSocketFrame) { closed = true; } listener.onFrame((WebSocketFrame) msg); ctx.pipeline().remove(this); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); listener.onError(cause); ctx.pipeline().remove(this); } }); ChannelFuture cf = ch.writeAndFlush(frame).syncUninterruptibly(); if (!cf.isSuccess()) { listener.onError(cf.cause()); } return this; }
From source file:io.vertx.benchmarks.HttpServerHandlerBenchmark.java
License:Open Source License
@Setup public void setup() { vertx = (VertxInternal) Vertx.vertx(); HttpServerOptions options = new HttpServerOptions(); vertxChannel = new EmbeddedChannel( new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()), new HttpResponseEncoder()); vertxChannel.config().setAllocator(new Alloc()); ContextInternal context = new EventLoopContext(vertx, vertxChannel.eventLoop(), null, null, null, new JsonObject(), Thread.currentThread().getContextClassLoader()); Handler<HttpServerRequest> app = request -> { HttpServerResponse response = request.response(); MultiMap headers = response.headers(); headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER) .add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH); response.end(HELLO_WORLD_BUFFER); };/* www . ja v a2s. com*/ HandlerHolder<HttpHandlers> holder = new HandlerHolder<>(context, new HttpHandlers(app, null, null, null)); Http1xServerHandler handler = new Http1xServerHandler(null, new HttpServerOptions(), "localhost", holder, null); vertxChannel.pipeline().addLast("handler", handler); nettyChannel = new EmbeddedChannel( new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()), new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() { private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8); private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length; private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled .unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT)); private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString( String.valueOf(STATIC_PLAINTEXT_LEN)); private final CharSequence TYPE_PLAIN = new AsciiString("text/plain"); private final CharSequence SERVER_NAME = new AsciiString("Netty"); private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE; private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE; private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH; private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER; private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); private final CharSequence date = new AsciiString(FORMAT.format(new Date())); @Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN, PLAINTEXT_CLHEADER_VALUE); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) { // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false); HttpHeaders headers = response.headers(); headers.set(CONTENT_TYPE_ENTITY, contentType); headers.set(SERVER_ENTITY, SERVER_NAME); headers.set(DATE_ENTITY, date); headers.set(CONTENT_LENGTH_ENTITY, contentLength); // Close the non-keep-alive connection after the write operation is done. ctx.write(response, ctx.voidPromise()); } }); nettyChannel.config().setAllocator(new Alloc()); GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes())); readerIndex = GET.readerIndex(); writeIndex = GET.writerIndex(); }
From source file:io.vertx.core.dns.impl.DnsClientImpl.java
License:Open Source License
@SuppressWarnings("unchecked") private <T> void lookup(String name, Future<List<T>> result, DnsRecordType... types) { Objects.requireNonNull(name, "no null name accepted"); bootstrap.connect(dnsServer).addListener(new RetryChannelFutureListener(result) { @Override/* w w w . j a v a2 s. co m*/ public void onSuccess(ChannelFuture future) throws Exception { DatagramDnsQuery query = new DatagramDnsQuery(null, dnsServer, ThreadLocalRandom.current().nextInt()); for (DnsRecordType type : types) { query.addRecord(DnsSection.QUESTION, new DefaultDnsQuestion(name, type, DnsRecord.CLASS_IN)); } future.channel().writeAndFlush(query).addListener(new RetryChannelFutureListener(result) { @Override public void onSuccess(ChannelFuture future) throws Exception { future.channel().pipeline().addLast(new SimpleChannelInboundHandler<DnsResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DnsResponse msg) throws Exception { DnsResponseCode code = DnsResponseCode.valueOf(msg.code().intValue()); if (code == DnsResponseCode.NOERROR) { int count = msg.count(DnsSection.ANSWER); List<T> records = new ArrayList<>(count); for (int idx = 0; idx < count; idx++) { DnsRecord a = msg.recordAt(DnsSection.ANSWER, idx); T record = RecordDecoder.decode(a); if (isRequestedType(a.type(), types)) { records.add(record); } } if (records.size() > 0 && (records.get(0) instanceof MxRecordImpl || records.get(0) instanceof SrvRecordImpl)) { Collections.sort((List) records); } setResult(result, records); } else { setFailure(result, new DnsException(code)); } ctx.close(); } private boolean isRequestedType(DnsRecordType dnsRecordType, DnsRecordType[] types) { for (DnsRecordType t : types) { if (t.equals(dnsRecordType)) { return true; } } return false; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { setFailure(result, cause); ctx.close(); } }); } }); } }); }
From source file:jj.repl.ReplIntegrationTest.java
License:Apache License
@Test public void test() throws Throwable { assertTrue("timed out waiting for init", latch.await(500, MILLISECONDS)); // well... it started so that's something // connect to config.port() and send in some commands? why not latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); final StringBuilder response = new StringBuilder().append("Welcome to JibbrJabbr\n>") .append("ReferenceError: \"whatever\" is not defined.\n").append(" at repl-console:1\n") .append(" at base-repl-system.js:8 ($$print)\n").append(" at repl-console:1\n").append("\n>"); bootstrap = new Bootstrap().group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override//from w ww . j a va 2s .co m protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder(US_ASCII)).addLast(new StringDecoder(US_ASCII)) .addLast(new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { if (msg.equals(response.substring(0, msg.length()))) { response.delete(0, msg.length()); } if (response.length() == 0) { latch.countDown(); } } }); } }); bootstrap.connect("localhost", config.port()).addListener((ChannelFuture future) -> { if (future.isSuccess()) { future.channel().writeAndFlush("whatever\n"); } else { failure.set(future.cause()); } }); assertTrue("timed out waiting for response", latch.await(1, SECONDS)); if (failure.get() != null) { throw failure.get(); } }
From source file:me.ferrybig.javacoding.teamspeakconnector.internal.TeamspeakIO.java
License:Open Source License
public void start() { if (this.con == null) { throw new IllegalStateException("No TeamspeakConnection registered"); }//w ww . j av a2 s . c om if (this.started) { throw new IllegalStateException("Already started"); } this.started = true; this.channel.pipeline().addLast(new SimpleChannelInboundHandler<ComplexResponse>() { private Throwable lastException = null; @Override protected void messageReceived(ChannelHandlerContext ctx, ComplexResponse msg) throws Exception { recievePacket(msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); lastException = cause; } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); channeClosed(lastException); } }); }
From source file:me.ferrybig.javacoding.teamspeakconnector.TeamspeakConnection.java
License:Open Source License
public void start() { this.io.registerConnection(this); this.io.start(); this.io.getChannel().pipeline().addLast(new SimpleChannelInboundHandler<Response>() { private Response lastPacket = null; //notifyclientleftview cfid=1 ctid=0 reasonid=8 reasonmsg=leaving clid=1 //notifycliententerview cfid=0 ctid=1 reasonid=0 clid=4 client_unique_identifier=P+m\/uXn4o2nLwN5gOimuQcfQZIQ= client_nickname=Ferrybig client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=0 client_output_hardware=1 client_meta_data client_is_recording=0 client_database_id=2 client_channel_group_id=5 client_servergroups=6,10 client_away=0 client_away_message client_type=0 client_flag_avatar=12f359409d033f5eebcc821a5dbcecf5 client_talk_power=75 client_talk_request=0 client_talk_request_msg client_description client_is_talker=0 client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic=Ferrybig client_needed_serverquery_view_power=75 client_icon_id=0 client_is_channel_commander=0 client_country client_channel_group_inherited_channel_id=1 client_badges=Overwolf=0 //notifyclientleftview cfid=72 ctid=0 reasonid=8 reasonmsg=leaving clid=4 //notifycliententerview cfid=0 ctid=1 reasonid=0 clid=5 client_unique_identifier=P+m\/uXn4o2nLwN5gOimuQcfQZIQ= client_nickname=Ferrybig client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=0 client_output_hardware=1 client_meta_data client_is_recording=0 client_database_id=2 client_channel_group_id=5 client_servergroups=6,10 client_away=0 client_away_message client_type=0 client_flag_avatar=12f359409d033f5eebcc821a5dbcecf5 client_talk_power=75 client_talk_request=0 client_talk_request_msg client_description client_is_talker=0 client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic=Ferrybig client_needed_serverquery_view_power=75 client_icon_id=0 client_is_channel_commander=0 client_country client_channel_group_inherited_channel_id=1 client_badges=Overwolf=0 @Override/*from w w w .j a v a2 s . co m*/ protected void messageReceived(ChannelHandlerContext ctx, Response msg) throws Exception { final Map<String, String> options = msg.getOptions(); LOG.log(Level.FINE, "Handling packet: {0}", msg); switch (msg.getCmd()) { case "notifytextmessage": { Future<User> whoami = io.whoAmI(); if (whoami.isSuccess()) { handleMessage(msg, whoami.get()); } else { whoami.addListener(f -> { assert f == whoami; LOG.fine("Handling delayed message delivery because whoami is not known"); handleMessage(msg, whoami.get()); }); } } break; case "notifycliententerview": { if (msg.equals(lastPacket)) { LOG.log(Level.FINE, "Dropping packet {0} because teamspeak usually sends dublicate packets when both channel and server listener is active", msg); lastPacket = null; return; } lastPacket = msg; options.put("cid", options.get("ctid")); ShallowUser client = io.mapShallowUser(options); UnresolvedChannel from = "0".equals(options.get("cfid")) ? null : getUnresolvedChannelById(parseInt(options.get("cfid"))); ChangeReason reason = ChangeReason.getById(parseInt(options.get("reasonid"))); ClientEnterViewEvent event; if (true && from == null) { event = new ClientEnterViewEvent(client, client.getChannel(), reason, null); serverHandler.callAll(ServerListener::onClientEnterView, event); } else { // TODO: channel change event } } break; case "notifyclientleftview": { // TODO: leave notification } break; case "notifyserveredited": { final int invokerId = Integer.parseInt(options.get("invokerid")); final String invokerName = options.get("invokername"); final String invokeruid = options.get("invokeruid"); serverHandler.callAll(ServerListener::onEditServer, new ServerEditEvent(ChangeReason.getById(parseInt(options.get("reasonid"))), getUnresolvedNamedUser(invokerId, invokerName, invokeruid))); } break; case "notifytokenused": { // clid=5 cldbid=4 cluid=zhPQ0oNLH8boM42jlbgTWC6G\\/64= token=4oquHhp03YKofI4dYVBLWZ9Ik+Mf0M6ogomh5RsU tokencustomset token1=7 token2=0 final UnresolvedUser client = getUnresolvedUserById(parseInt(options.get("clid"))); final int databaseId = parseInt(options.get("cldbid")); final String uniqueId = options.get("cluid"); final String token = options.get("token"); final String tokencustomset = options.get("tokencustomset"); final String token1 = options.get("token1"); final String token2 = options.get("token2"); tokenUsedHandler.callAll(TokenListener::onTokenUsed, new TokenUsedEvent(client, databaseId, uniqueId, token, tokencustomset, token1, token2)); } break; default: { LOG.log(Level.WARNING, "Unhandled packet: {0}", msg); } } } }); }