├── .gitignore ├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── file.txt ├── lib └── bin │ └── lib │ └── x86_64-MacOSX-gpp │ └── jni │ └── libbarchart-udt-core-2.3.0-SNAPSHOT.jnilib ├── license └── LICENSE.netty.txt ├── pom.xml └── src └── main ├── java └── com │ ├── flydean01 │ └── first │ │ ├── FirstClient.java │ │ ├── FirstClientHandler.java │ │ ├── FirstServer.java │ │ └── FirstServerHandler.java │ ├── flydean02 │ └── bytebuf │ │ └── ByteBufUsage.java │ ├── flydean03 │ └── handler │ │ └── MyHandler.java │ ├── flydean06 │ └── cheerup │ │ ├── CheerUpServer.java │ │ ├── CheerUpServerHandler.java │ │ ├── ChinaClient.java │ │ └── ChinaClientHandler.java │ ├── flydean08 │ └── pojo │ │ ├── PojoClient.java │ │ ├── PojoClientHandler.java │ │ ├── PojoServer.java │ │ └── PojoServerHandler.java │ ├── flydean09 │ └── reconnect │ │ ├── ReconnectClient.java │ │ ├── ReconnectClientHandler.java │ │ ├── ReconnectServer.java │ │ └── ReconnectServerHandler.java │ ├── flydean10 │ └── chat │ │ ├── ChatClient.java │ │ ├── ChatClientHandler.java │ │ ├── ChatClientInitializer.java │ │ ├── ChatServer.java │ │ ├── ChatServerHandler.java │ │ └── ChatServerInitializer.java │ ├── flydean11 │ └── udp │ │ ├── UDPClient.java │ │ ├── UDPClientHandler.java │ │ ├── UDPServer.java │ │ └── UDPServerHandler.java │ ├── flydean12 │ └── securechat │ │ ├── SecureChatClient.java │ │ ├── SecureChatClient2.java │ │ ├── SecureChatClientHandler.java │ │ ├── SecureChatClientInitializer.java │ │ ├── SecureChatServer.java │ │ ├── SecureChatServerHandler.java │ │ └── SecureChatServerInitializer.java │ ├── flydean13 │ └── customprotocol │ │ ├── CustomProtocolClient.java │ │ ├── CustomProtocolClientHandler.java │ │ ├── CustomProtocolClientInitializer.java │ │ ├── CustomProtocolServer.java │ │ ├── CustomProtocolServerHandler.java │ │ ├── CustomProtocolServerInitializer.java │ │ ├── NumberDecoder.java │ │ └── NumberEncoder.java │ ├── flydean14 │ └── custcodec │ │ ├── IntegerEncoder.java │ │ ├── IntegerHeaderFrameDecoder.java │ │ ├── IntegerHeaderFrameDecoderReplay.java │ │ ├── IntegerHeaderFrameDecoderSteps.java │ │ ├── IntegerToStringEncoder.java │ │ ├── MyDecoderState.java │ │ ├── SquareDecoder.java │ │ └── StringToIntegerDecoder.java │ ├── flydean17 │ ├── marshalling │ │ ├── MarshallingReader.java │ │ ├── MarshallingWriter.java │ │ └── Student.java │ └── protobuf │ │ ├── Student.java │ │ ├── StudentClient.java │ │ ├── StudentClientHandler.java │ │ ├── StudentClientInitializer.java │ │ ├── StudentOrBuilder.java │ │ ├── StudentOuterClass.java │ │ ├── StudentServer.java │ │ ├── StudentServerHandler.java │ │ ├── StudentServerInitializer.java │ │ └── student.proto │ ├── flydean18 │ └── httprequest │ │ ├── HttpRequestServer.java │ │ ├── HttpRequestServerHandler.java │ │ └── HttpRequestServerInitializer.java │ ├── flydean19 │ └── httpclientrequest │ │ ├── ClientRequestClient.java │ │ ├── ClientRequestClientHandler.java │ │ ├── ClientRequestClientInitializer.java │ │ ├── HttpRequestServer.java │ │ ├── HttpRequestServerHandler.java │ │ └── HttpRequestServerInitializer.java │ ├── flydean20 │ └── httpfile │ │ ├── HttpFileServer.java │ │ ├── HttpFileServerHandler.java │ │ └── HttpFileServerInitializer.java │ ├── flydean21 │ └── httpupload │ │ ├── HttpUploadClient.java │ │ ├── HttpUploadClientHandler.java │ │ ├── HttpUploadClientInitializer.java │ │ ├── HttpUploadServer.java │ │ ├── HttpUploadServerHandler.java │ │ └── HttpUploadServerInitializer.java │ ├── flydean22 │ └── cors │ │ ├── CustResponseHandler.java │ │ ├── HttpCorsServer.java │ │ └── HttpCorsServerInitializer.java │ ├── flydean23 │ └── socketserver │ │ ├── TestSocketHttpPage.java │ │ ├── TestSocketServer.java │ │ ├── TestSocketServerHandler.java │ │ └── TestSocketServerInitializer.java │ ├── flydean24 │ └── socketserver2 │ │ ├── Server2FrameHandler.java │ │ ├── Server2HttpHandler.java │ │ ├── Server2HttpPage.java │ │ ├── Server2Initializer.java │ │ └── Server2Server.java │ ├── flydean25 │ └── socketclient │ │ ├── TestSocketClient.java │ │ └── TestSocketClientHandler.java │ ├── flydean26 │ └── http2server │ │ ├── CustHttp1Handler.java │ │ ├── CustHttp2Handler.java │ │ ├── CustHttp2HandlerBuilder.java │ │ ├── CustHttp2Server.java │ │ ├── CustHttp2ServerInitializer.java │ │ └── CustProtocolNegotiationHandler.java │ ├── flydean30 │ └── http2client │ │ ├── CustHttp2Client.java │ │ ├── CustHttp2ClientInitializer.java │ │ ├── CustHttp2SettingsHandler.java │ │ ├── CustHttpResponseHandler.java │ │ └── CustUpgradeRequestHandler.java │ ├── flydean31 │ └── http2framecodecserver │ │ ├── CustHttp1Handler.java │ │ ├── CustHttp2Handler.java │ │ ├── CustHttp2Server.java │ │ ├── CustHttp2ServerInitializer.java │ │ └── CustProtocolNegotiationHandler.java │ ├── flydean32 │ └── http2framecodecclient │ │ ├── Http2ClientFrameInitializer.java │ │ ├── Http2ClientStreamFrameHandler.java │ │ └── Http2FrameClient.java │ ├── flydean33 │ └── http2multiplexserver │ │ ├── CustMultiplexHttp2Handler.java │ │ ├── MultiplexHttp2Server.java │ │ ├── MultiplexHttp2ServerInitializer.java │ │ └── MultiplexProtocolNegotiationHandler.java │ ├── flydean34 │ └── http2images │ │ ├── CustProtocolNegotiationHandler.java │ │ ├── Http1RequestHandler.java │ │ ├── Http2RequestHandler.java │ │ ├── ImageHttp1Server.java │ │ ├── ImageHttp2Server.java │ │ ├── ImagePage.java │ │ └── ImageServer.java │ ├── flydean35 │ └── proxy │ │ ├── SimpleDumpProxy.java │ │ ├── SimpleDumpProxyInboundHandler.java │ │ ├── SimpleDumpProxyInitializer.java │ │ └── SimpleDumpProxyOutboundHandler.java │ ├── flydean36 │ └── socksproxy │ │ ├── ClientPromiseHandler.java │ │ ├── RelayHandler.java │ │ ├── SocksServer.java │ │ ├── SocksServerConnectHandler.java │ │ ├── SocksServerHandler.java │ │ └── SocksServerInitializer.java │ ├── flydean37 │ └── custportunification │ │ ├── CustPortUnificationServer.java │ │ └── CustPortUnificationServerHandler.java │ ├── flydean40 │ └── udtByte │ │ ├── UDTByteEchoClient.java │ │ ├── UDTByteEchoClientHandler.java │ │ ├── UDTByteEchoServer.java │ │ └── UDTByteEchoServerHandler.java │ ├── flydean41 │ └── udtMessage │ │ ├── UDTMsgEchoClient.java │ │ ├── UDTMsgEchoClientHandler.java │ │ ├── UDTMsgEchoServer.java │ │ └── UDTMsgEchoServerHandler.java │ ├── flydean42 │ └── udtRendezvous │ │ ├── UDTByteHandler.java │ │ ├── UDTByteRendezvousBase.java │ │ ├── UDTByteRendezvousOne.java │ │ ├── UDTByteRendezvousTwo.java │ │ ├── UDTMsgHandler.java │ │ ├── UDTMsgRendezvousBase.java │ │ ├── UDTMsgRendezvousOne.java │ │ └── UDTMsgRendezvousTwo.java │ ├── flydean43 │ └── byteBufRef │ │ └── ByteBufRef.java │ ├── flydean44 │ └── tfo │ │ ├── TFOClient.java │ │ ├── TFOClientHandler.java │ │ ├── TFOServer.java │ │ └── TFOServerHandler.java │ ├── flydean49 │ └── extendEnum │ │ ├── Programmer.java │ │ ├── StatusEnum.java │ │ └── SumEnum.java │ ├── flydean51 │ └── affinity │ │ ├── AffinityServer.java │ │ └── AffinityServerHandler.java │ ├── flydean52 │ └── nativetransport │ │ ├── epoll │ │ ├── NativeChatClient.java │ │ ├── NativeChatClientHandler.java │ │ ├── NativeChatClientInitializer.java │ │ ├── NativeChatServer.java │ │ ├── NativeChatServerHandler.java │ │ └── NativeChatServerInitializer.java │ │ └── kqueue │ │ ├── NativeChatClient.java │ │ ├── NativeChatClientHandler.java │ │ ├── NativeChatClientInitializer.java │ │ ├── NativeChatServer.java │ │ ├── NativeChatServerHandler.java │ │ └── NativeChatServerInitializer.java │ ├── flydean54 │ └── dnstcp │ │ ├── Do53TcpChannelInboundHandler.java │ │ ├── Do53TcpChannelInitializer.java │ │ └── Do53TcpClient.java │ ├── flydean55 │ └── dnsudp │ │ ├── Do53UdpChannelInboundHandler.java │ │ ├── Do53UdpChannelInitializer.java │ │ └── Do53UdpClient.java │ ├── flydean56 │ └── dnsdot │ │ ├── DoTClient.java │ │ ├── DotChannelInboundHandler.java │ │ └── DotChannelInitializer.java │ ├── flydean57 │ └── dnsserver │ │ ├── Do53ServerChannelInitializer.java │ │ ├── Do53ServerInboundHandler.java │ │ ├── Do53TcpClient.java │ │ └── Do53TcpServer.java │ ├── flydean58 │ └── proxyprotocol │ │ ├── ClientHander.java │ │ ├── ProxyProtocolClient.java │ │ ├── ProxyProtocolServer.java │ │ └── ServerInitializer.java │ ├── flydean59 │ └── sctp │ │ ├── SctpChatClient.java │ │ ├── SctpChatClientHandler.java │ │ ├── SctpChatServer.java │ │ ├── SctpChatServerHandler.java │ │ ├── SctpMultiHomingChatClient.java │ │ └── SctpMultiHomingChatServer.java │ ├── flydean61 │ └── memcached │ │ ├── MemcachedClient.java │ │ ├── MemcachedClientHandler.java │ │ └── MemcachedInitializer.java │ ├── flydean62 │ └── redis │ │ ├── RedisChannelInitializer.java │ │ ├── RedisClient.java │ │ └── RedisClientHandler.java │ ├── flydean64 │ └── mqttbroker │ │ ├── MqttCustBroker.java │ │ ├── MqttCustBrokerHandler.java │ │ └── MqttCustBrokerInitializer.java │ ├── flydean65 │ └── mqttclient │ │ ├── MqttClient.java │ │ ├── MqttClientChannelInitializer.java │ │ └── MqttClientHandler.java │ ├── flydean67 │ └── ocspclient │ │ ├── CustOcspClientHandler.java │ │ ├── OcspClient.java │ │ ├── OcspClientHandlerAdapter.java │ │ └── OcspClientInitializer.java │ ├── flydean68 │ └── ocspstapling │ │ ├── OcspRequestBuilder.java │ │ ├── OcspStaplingClient.java │ │ ├── OcspUtils.java │ │ └── SHA1DigestCalculator.java │ └── flydean69 │ └── stomp │ ├── StompClient.java │ └── StompClientHandler.java └── resources ├── com └── flydean34 │ └── http2images │ ├── image.html │ ├── img0.jpg │ ├── img1.jpg │ ├── img2.jpg │ ├── img3.jpg │ ├── img4.jpg │ └── img5.jpg ├── logback.xml ├── socket.html └── socket2.html /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | 33 | .DS_Store 34 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | 2 | Learn Netty4 Project 3 | ================= 4 | 5 | Please visit the flydean web site for more information: 6 | 7 | * http://www.flydean.com/ 8 | 9 | Copyright 2022 learn-netty4 Project 10 | 11 | The learn-netty4 Project licenses this file to you under the Apache License, 12 | version 2.0 (the "License"); you may not use this file except in compliance 13 | with the License. You may obtain a copy of the License at: 14 | 15 | https://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 19 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 20 | License for the specific language governing permissions and limitations 21 | under the License. 22 | 23 | Also, please refer to each LICENSE..txt file, which is located in 24 | the 'license' directory of the distribution file, for the license terms of the 25 | components that this product depends on. 26 | 27 | ------------------------------------------------------------------------------- 28 | This project contains a modified portion of 'Netty Project',an asynchronous 29 | event-driven network application framework,which can be obtained at: 30 | 31 | * LICENSE: 32 | * license/LICENSE.netty.txt (Apache License 2.0) 33 | * HOMEPAGE: 34 | * https://github.com/netty/netty 35 | -------------------------------------------------------------------------------- /lib/bin/lib/x86_64-MacOSX-gpp/jni/libbarchart-udt-core-2.3.0-SNAPSHOT.jnilib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/lib/bin/lib/x86_64-MacOSX-gpp/jni/libbarchart-udt-core-2.3.0-SNAPSHOT.jnilib -------------------------------------------------------------------------------- /license/LICENSE.netty.txt: -------------------------------------------------------------------------------- 1 | The Netty Project 2 | ================= 3 | 4 | Please visit the Netty web site for more information: 5 | 6 | * https://netty.io/ 7 | 8 | Copyright 2014 The Netty Project 9 | 10 | The Netty Project licenses this file to you under the Apache License, 11 | version 2.0 (the "License"); you may not use this file except in compliance 12 | with the License. You may obtain a copy of the License at: 13 | 14 | https://www.apache.org/licenses/LICENSE-2.0 15 | 16 | Unless required by applicable law or agreed to in writing, software 17 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 18 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 19 | License for the specific language governing permissions and limitations 20 | under the License. -------------------------------------------------------------------------------- /src/main/java/com/flydean01/first/FirstClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean01.first; 17 | 18 | import io.netty.bootstrap.Bootstrap; 19 | import io.netty.channel.ChannelFuture; 20 | import io.netty.channel.ChannelInitializer; 21 | import io.netty.channel.ChannelPipeline; 22 | import io.netty.channel.EventLoopGroup; 23 | import io.netty.channel.nio.NioEventLoopGroup; 24 | import io.netty.channel.socket.SocketChannel; 25 | import io.netty.channel.socket.nio.NioSocketChannel; 26 | 27 | /** 28 | * 第一个netty的客户端 29 | */ 30 | public final class FirstClient { 31 | 32 | static final String HOST = System.getProperty("host", "127.0.0.1"); 33 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 34 | 35 | public static void main(String[] args) throws Exception { 36 | 37 | EventLoopGroup group = new NioEventLoopGroup(); 38 | try { 39 | Bootstrap b = new Bootstrap(); 40 | b.group(group) 41 | .channel(NioSocketChannel.class) 42 | .handler(new ChannelInitializer() { 43 | @Override 44 | protected void initChannel(SocketChannel ch) throws Exception { 45 | ChannelPipeline p = ch.pipeline(); 46 | p.addLast(new FirstClientHandler()); 47 | } 48 | }); 49 | 50 | // 连接服务器 51 | ChannelFuture f = b.connect(HOST, PORT).sync(); 52 | 53 | // 等待关闭 54 | f.channel().closeFuture().sync(); 55 | } finally { 56 | group.shutdownGracefully(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/flydean01/first/FirstClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean01.first; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.*; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | import java.nio.charset.StandardCharsets; 23 | 24 | /** 25 | * Handles a client-side channel. 26 | */ 27 | @Slf4j 28 | public class FirstClientHandler extends ChannelInboundHandlerAdapter { 29 | 30 | private ByteBuf content; 31 | private ChannelHandlerContext ctx; 32 | 33 | @Override 34 | public void channelActive(ChannelHandlerContext ctx) { 35 | this.ctx = ctx; 36 | content = ctx.alloc().directBuffer(256).writeBytes("Hello flydean.com".getBytes(StandardCharsets.UTF_8)); 37 | // 发送消息 38 | sayHello(); 39 | } 40 | 41 | @Override 42 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 43 | // 异常处理 44 | log.error("出现异常",cause); 45 | ctx.close(); 46 | } 47 | 48 | private void sayHello() { 49 | // 向服务器输出消息 50 | ctx.writeAndFlush(content.retain()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean01/first/FirstServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean01.first; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import io.netty.util.ReferenceCountUtil; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | /** 25 | * @author wayne 26 | * @version FirstServer, 2021/8/1 27 | */ 28 | @Slf4j 29 | public class FirstServerHandler extends ChannelInboundHandlerAdapter { 30 | @Override 31 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 32 | // 对消息进行处理 33 | ByteBuf in = (ByteBuf) msg; 34 | try { 35 | log.info("收到消息:{}",in.toString(io.netty.util.CharsetUtil.US_ASCII)); 36 | }finally { 37 | ReferenceCountUtil.release(msg); 38 | } 39 | } 40 | 41 | @Override 42 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 43 | // 异常处理 44 | log.error("出现异常",cause); 45 | ctx.close(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/flydean02/bytebuf/ByteBufUsage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean02.bytebuf; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | 20 | import java.util.Random; 21 | 22 | import static io.netty.buffer.Unpooled.*; 23 | 24 | /** 25 | * @author wayne 26 | * @version ByteBufUsage, 2021/8/2 27 | */ 28 | public class ByteBufUsage { 29 | 30 | public static void main(String[] args) { 31 | //创建ByteBuf 32 | ByteBuf heapBuffer = buffer(128); 33 | ByteBuf directBuffer = directBuffer(256); 34 | ByteBuf wrappedBuffer = wrappedBuffer(new byte[128], new byte[256]); 35 | 36 | //随机访问 37 | ByteBuf buffer = heapBuffer; 38 | for (int i = 0; i < buffer.capacity(); i ++) { 39 | byte b = buffer.getByte(i); 40 | System.out.println((char) b); 41 | } 42 | 43 | //遍历readable bytes 44 | while (directBuffer.isReadable()) { 45 | System.out.println(directBuffer.readByte()); 46 | } 47 | 48 | //写入writable bytes 49 | while (wrappedBuffer.maxWritableBytes() >= 4) { 50 | wrappedBuffer.writeInt(new Random().nextInt()); 51 | } 52 | 53 | 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean03/handler/MyHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean03.handler; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import io.netty.util.ReferenceCountUtil; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | /** 25 | * Handles a server-side channel. 26 | */ 27 | @Slf4j 28 | public class MyHandler extends SimpleChannelInboundHandler { 29 | 30 | @Override 31 | public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { 32 | // 对消息进行处理 33 | ByteBuf in = (ByteBuf) msg; 34 | try { 35 | log.info("收到消息:{}",in.toString(io.netty.util.CharsetUtil.US_ASCII)); 36 | }finally { 37 | ReferenceCountUtil.release(msg); 38 | } 39 | } 40 | 41 | @Override 42 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 43 | //异常处理 44 | cause.printStackTrace(); 45 | ctx.close(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/flydean08/pojo/PojoServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean08.pojo; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.ChannelInboundHandlerAdapter; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | /** 23 | * 处理客户端发来的消息 24 | */ 25 | @Slf4j 26 | public class PojoServerHandler extends ChannelInboundHandlerAdapter { 27 | 28 | @Override 29 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 30 | log.info("server收到对象:{}",msg); 31 | ctx.write("加油!"); 32 | } 33 | 34 | @Override 35 | public void channelReadComplete(ChannelHandlerContext ctx) { 36 | ctx.flush(); 37 | } 38 | 39 | @Override 40 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 41 | // 异常处理 42 | log.error("出现异常",cause); 43 | ctx.close(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/flydean09/reconnect/ReconnectServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean09.reconnect; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | @Sharable 24 | @Slf4j 25 | public class ReconnectServerHandler extends SimpleChannelInboundHandler { 26 | @Override 27 | public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { 28 | // 读取消息 29 | } 30 | 31 | @Override 32 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 33 | // 异常处理 34 | log.error("出现异常",cause); 35 | ctx.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/flydean10/chat/ChatClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean10.chat; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | /** 24 | * 客户端处理器 25 | */ 26 | @Sharable 27 | @Slf4j 28 | public class ChatClientHandler extends SimpleChannelInboundHandler { 29 | 30 | @Override 31 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 32 | log.info("client accepted channel: {}", ctx.channel()); 33 | log.info("接收到消息:{}",msg); 34 | } 35 | 36 | @Override 37 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 38 | // 异常处理 39 | log.error("出现异常",cause); 40 | ctx.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/flydean10/chat/ChatClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean10.chat; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | 26 | /** 27 | * 客户端ChannelPipeline的配置 28 | */ 29 | public class ChatClientInitializer extends ChannelInitializer { 30 | 31 | private static final StringDecoder DECODER = new StringDecoder(); 32 | private static final StringEncoder ENCODER = new StringEncoder(); 33 | 34 | private static final ChatClientHandler CLIENT_HANDLER = new ChatClientHandler(); 35 | 36 | @Override 37 | public void initChannel(SocketChannel ch) { 38 | ChannelPipeline pipeline = ch.pipeline(); 39 | 40 | // 添加行分割器 41 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 42 | pipeline.addLast(DECODER); 43 | pipeline.addLast(ENCODER); 44 | 45 | // 添加客户端处理器 46 | pipeline.addLast(CLIENT_HANDLER); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean10/chat/ChatServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean10.chat; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import io.netty.handler.logging.LogLevel; 24 | import io.netty.handler.logging.LoggingHandler; 25 | import lombok.extern.slf4j.Slf4j; 26 | 27 | /** 28 | * chat 服务器 29 | */ 30 | @Slf4j 31 | public final class ChatServer { 32 | 33 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 34 | 35 | public static void main(String[] args) throws Exception { 36 | 37 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 38 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 39 | try { 40 | ServerBootstrap b = new ServerBootstrap(); 41 | b.group(bossGroup, workerGroup) 42 | .channel(NioServerSocketChannel.class) 43 | .handler(new LoggingHandler(LogLevel.INFO)) 44 | .childHandler(new ChatServerInitializer()); 45 | 46 | Channel channel = b.bind(PORT).sync().channel(); 47 | log.info("server channel:{}", channel); 48 | channel.closeFuture().sync(); 49 | } finally { 50 | bossGroup.shutdownGracefully(); 51 | workerGroup.shutdownGracefully(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/flydean10/chat/ChatServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean10.chat; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | 26 | /** 27 | * 初始化一个ChannelPipeline 28 | */ 29 | public class ChatServerInitializer extends ChannelInitializer { 30 | 31 | private static final StringDecoder DECODER = new StringDecoder(); 32 | private static final StringEncoder ENCODER = new StringEncoder(); 33 | 34 | private static final ChatServerHandler SERVER_HANDLER = new ChatServerHandler(); 35 | 36 | @Override 37 | public void initChannel(SocketChannel ch) throws Exception { 38 | ChannelPipeline pipeline = ch.pipeline(); 39 | // 添加行分割器 40 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 41 | // 添加String Decoder和String Encoder,用来进行字符串的转换 42 | pipeline.addLast(DECODER); 43 | pipeline.addLast(ENCODER); 44 | // 最后添加真正的处理器 45 | pipeline.addLast(SERVER_HANDLER); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/flydean11/udp/UDPClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean11.udp; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.SimpleChannelInboundHandler; 20 | import io.netty.channel.socket.DatagramPacket; 21 | import io.netty.util.CharsetUtil; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | @Slf4j 25 | public class UDPClientHandler extends SimpleChannelInboundHandler { 26 | 27 | @Override 28 | public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { 29 | String response = msg.content().toString(CharsetUtil.UTF_8); 30 | if (response.startsWith("广播: ")) { 31 | log.info("收到广播: {}", response.substring(4)); 32 | ctx.close(); 33 | } 34 | } 35 | 36 | @Override 37 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 38 | cause.printStackTrace(); 39 | ctx.close(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/flydean11/udp/UDPServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean11.udp; 17 | 18 | import io.netty.bootstrap.Bootstrap; 19 | import io.netty.channel.ChannelOption; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioDatagramChannel; 23 | 24 | /** 25 | * UDP 服务器 26 | */ 27 | public final class UDPServer { 28 | 29 | private static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 30 | 31 | public static void main(String[] args) throws Exception { 32 | EventLoopGroup group = new NioEventLoopGroup(); 33 | try { 34 | Bootstrap b = new Bootstrap(); 35 | b.group(group) 36 | .channel(NioDatagramChannel.class) 37 | .option(ChannelOption.SO_BROADCAST, true) 38 | .handler(new UDPServerHandler()); 39 | 40 | b.bind(PORT).sync().channel().closeFuture().await(); 41 | } finally { 42 | group.shutdownGracefully(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/flydean12/securechat/SecureChatClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean12.securechat; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | /** 24 | * 客户端处理器 25 | */ 26 | @Sharable 27 | @Slf4j 28 | public class SecureChatClientHandler extends SimpleChannelInboundHandler { 29 | 30 | @Override 31 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 32 | log.info("接收到消息:{}",msg); 33 | } 34 | 35 | @Override 36 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 37 | // 异常处理 38 | log.error("出现异常",cause); 39 | ctx.close(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/flydean12/securechat/SecureChatClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean12.securechat; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | import io.netty.handler.ssl.SslContext; 26 | 27 | /** 28 | * 客户端ChannelPipeline的配置 29 | */ 30 | public class SecureChatClientInitializer extends ChannelInitializer { 31 | 32 | private static final StringDecoder DECODER = new StringDecoder(); 33 | private static final StringEncoder ENCODER = new StringEncoder(); 34 | 35 | private static final SecureChatClientHandler CLIENT_HANDLER = new SecureChatClientHandler(); 36 | 37 | private final SslContext sslCtx; 38 | 39 | public SecureChatClientInitializer(SslContext sslCtx){ 40 | this.sslCtx = sslCtx; 41 | } 42 | 43 | @Override 44 | public void initChannel(SocketChannel ch) { 45 | ChannelPipeline pipeline = ch.pipeline(); 46 | 47 | // 添加SSL处理机制 48 | pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT)); 49 | 50 | // 添加行分割器 51 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 52 | pipeline.addLast(DECODER); 53 | pipeline.addLast(ENCODER); 54 | 55 | // 添加客户端处理器 56 | pipeline.addLast(CLIENT_HANDLER); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/flydean12/securechat/SecureChatServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean12.securechat; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | import io.netty.handler.ssl.SslContext; 26 | 27 | /** 28 | * 初始化一个ChannelPipeline 29 | */ 30 | public class SecureChatServerInitializer extends ChannelInitializer { 31 | 32 | private static final StringDecoder DECODER = new StringDecoder(); 33 | private static final StringEncoder ENCODER = new StringEncoder(); 34 | 35 | private static final SecureChatServerHandler SERVER_HANDLER = new SecureChatServerHandler(); 36 | 37 | private final SslContext sslCtx; 38 | 39 | public SecureChatServerInitializer(SslContext sslCtx){ 40 | this.sslCtx = sslCtx; 41 | } 42 | 43 | @Override 44 | public void initChannel(SocketChannel ch) throws Exception { 45 | ChannelPipeline pipeline = ch.pipeline(); 46 | 47 | //添加SSL处理器 48 | pipeline.addLast(sslCtx.newHandler(ch.alloc())); 49 | // 添加行分割器 50 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 51 | // 添加String Decoder和String Encoder,用来进行字符串的转换 52 | pipeline.addLast(DECODER); 53 | pipeline.addLast(ENCODER); 54 | // 最后添加真正的处理器 55 | pipeline.addLast(SERVER_HANDLER); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/CustomProtocolClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.bootstrap.Bootstrap; 19 | import io.netty.channel.ChannelFuture; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioSocketChannel; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | /** 26 | * 自定义协议客户端 27 | */ 28 | @Slf4j 29 | public final class CustomProtocolClient { 30 | 31 | static final String HOST = System.getProperty("host", "127.0.0.1"); 32 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 33 | static final int COUNT = Integer.parseInt(System.getProperty("count", "100")); 34 | 35 | public static void main(String[] args) throws Exception { 36 | EventLoopGroup group = new NioEventLoopGroup(); 37 | try { 38 | Bootstrap b = new Bootstrap(); 39 | b.group(group) 40 | .channel(NioSocketChannel.class) 41 | .handler(new CustomProtocolClientInitializer()); 42 | 43 | // 建立连接 44 | ChannelFuture f = b.connect(HOST, PORT).sync(); 45 | 46 | // 获取自定义handler 47 | CustomProtocolClientHandler handler = 48 | (CustomProtocolClientHandler) f.channel().pipeline().last(); 49 | 50 | // 打印结果 51 | log.info("2的{}次方是:{}",COUNT, handler.getResult()); 52 | } finally { 53 | group.shutdownGracefully(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/CustomProtocolClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.compression.ZlibCodecFactory; 22 | import io.netty.handler.codec.compression.ZlibWrapper; 23 | 24 | /** 25 | * 客户端pipeline初始化器 26 | */ 27 | public class CustomProtocolClientInitializer extends ChannelInitializer { 28 | 29 | @Override 30 | public void initChannel(SocketChannel ch) { 31 | ChannelPipeline pipeline = ch.pipeline(); 32 | 33 | // stream压缩 34 | pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP)); 35 | pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); 36 | 37 | // 添加Number编码器 38 | pipeline.addLast(new NumberDecoder()); 39 | pipeline.addLast(new NumberEncoder()); 40 | 41 | // 最后添加业务逻辑 42 | pipeline.addLast(new CustomProtocolClientHandler()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/CustomProtocolServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.EventLoopGroup; 20 | import io.netty.channel.nio.NioEventLoopGroup; 21 | import io.netty.channel.socket.nio.NioServerSocketChannel; 22 | import io.netty.handler.logging.LogLevel; 23 | import io.netty.handler.logging.LoggingHandler; 24 | 25 | /** 26 | * 自定义协议服务器 27 | */ 28 | public final class CustomProtocolServer { 29 | 30 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 31 | 32 | public static void main(String[] args) throws Exception { 33 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 34 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 35 | try { 36 | ServerBootstrap b = new ServerBootstrap(); 37 | b.group(bossGroup, workerGroup) 38 | .channel(NioServerSocketChannel.class) 39 | .handler(new LoggingHandler(LogLevel.INFO)) 40 | .childHandler(new CustomProtocolServerInitializer()); 41 | 42 | b.bind(PORT).sync().channel().closeFuture().sync(); 43 | } finally { 44 | bossGroup.shutdownGracefully(); 45 | workerGroup.shutdownGracefully(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/CustomProtocolServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.SimpleChannelInboundHandler; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | import java.math.BigInteger; 23 | 24 | /** 25 | * 自定义协议处理器 26 | */ 27 | @Slf4j 28 | public class CustomProtocolServerHandler extends SimpleChannelInboundHandler { 29 | 30 | private int count = 0; 31 | private BigInteger result=BigInteger.valueOf(1); 32 | 33 | @Override 34 | public void channelRead0(ChannelHandlerContext ctx, BigInteger msg) throws Exception { 35 | // 将接收到的msg乘以2,然后返回给客户端 36 | count++; 37 | result = result.multiply(msg); 38 | ctx.writeAndFlush(result); 39 | } 40 | 41 | @Override 42 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 43 | log.info("2的{}次方是{}",count,result); 44 | } 45 | 46 | @Override 47 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 48 | // 异常处理 49 | log.error("出现异常",cause); 50 | ctx.close(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/CustomProtocolServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.compression.ZlibCodecFactory; 22 | import io.netty.handler.codec.compression.ZlibWrapper; 23 | 24 | /** 25 | * 服务器端pipeline初始化 26 | */ 27 | public class CustomProtocolServerInitializer extends ChannelInitializer { 28 | 29 | @Override 30 | public void initChannel(SocketChannel ch) { 31 | ChannelPipeline pipeline = ch.pipeline(); 32 | 33 | // 对流进行压缩 34 | pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP)); 35 | pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); 36 | 37 | // 添加number编码解码器 38 | pipeline.addLast(new NumberDecoder()); 39 | pipeline.addLast(new NumberEncoder()); 40 | 41 | // 添加业务处理逻辑 42 | pipeline.addLast(new CustomProtocolServerHandler()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/NumberDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.ByteToMessageDecoder; 21 | import io.netty.handler.codec.CorruptedFrameException; 22 | 23 | import java.math.BigInteger; 24 | import java.util.List; 25 | 26 | /** 27 | * 将编码过后的byte[] 转换成BigInteger对象 28 | */ 29 | public class NumberDecoder extends ByteToMessageDecoder { 30 | 31 | @Override 32 | protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { 33 | // 保证魔法词和数组长度有效 34 | if (in.readableBytes() < 5) { 35 | return; 36 | } 37 | in.markReaderIndex(); 38 | // 检查魔法词 39 | int magicNumber = in.readUnsignedByte(); 40 | if (magicNumber != 'N') { 41 | in.resetReaderIndex(); 42 | throw new CorruptedFrameException("无效的魔法词: " + magicNumber); 43 | } 44 | // 读取所有的数据 45 | int dataLength = in.readInt(); 46 | if (in.readableBytes() < dataLength) { 47 | in.resetReaderIndex(); 48 | return; 49 | } 50 | // 将剩下的数据转换成为BigInteger 51 | byte[] decoded = new byte[dataLength]; 52 | in.readBytes(decoded); 53 | out.add(new BigInteger(decoded)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/flydean13/customprotocol/NumberEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean13.customprotocol; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.MessageToByteEncoder; 21 | 22 | import java.math.BigInteger; 23 | 24 | /** 25 | * 将Number编码成byte[]格式,第一个byte表示魔法词"N", 26 | * 接下来的4个byte代表数组的长度 27 | * 最后的才是真正的数字 28 | */ 29 | public class NumberEncoder extends MessageToByteEncoder { 30 | 31 | @Override 32 | protected void encode(ChannelHandlerContext ctx, Number msg, ByteBuf out) { 33 | // 将number编码成为ByteBuf 34 | BigInteger v; 35 | if (msg instanceof BigInteger) { 36 | v = (BigInteger) msg; 37 | } else { 38 | v = new BigInteger(String.valueOf(msg)); 39 | } 40 | 41 | // 将BigInteger转换成为byte[]数组 42 | byte[] data = v.toByteArray(); 43 | int dataLength = data.length; 44 | 45 | // 将Number进行编码 46 | out.writeByte((byte) 'N'); // 魔法词 47 | out.writeInt(dataLength); // 数组长度 48 | out.writeBytes(data); // 最终的数据 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/IntegerEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.MessageToByteEncoder; 21 | 22 | /** 23 | * @author wayne 24 | * @version IntegerEncoder, 2021/8/13 25 | */ 26 | public class IntegerEncoder extends MessageToByteEncoder { 27 | @Override 28 | public void encode(ChannelHandlerContext ctx, Integer msg, ByteBuf out) 29 | throws Exception { 30 | out.writeInt(msg); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/IntegerHeaderFrameDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.ByteToMessageDecoder; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * @author wayne 26 | * @version IntegerHeaderFrameDecoder, 2021/8/13 27 | */ 28 | public class IntegerHeaderFrameDecoder extends ByteToMessageDecoder { 29 | 30 | @Override 31 | protected void decode(ChannelHandlerContext ctx, 32 | ByteBuf buf, List out) throws Exception { 33 | 34 | if (buf.readableBytes() < 4) { 35 | return; 36 | } 37 | 38 | buf.markReaderIndex(); 39 | int length = buf.readInt(); 40 | 41 | if (buf.readableBytes() < length) { 42 | buf.resetReaderIndex(); 43 | return; 44 | } 45 | 46 | out.add(buf.readBytes(length)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/IntegerHeaderFrameDecoderReplay.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.ReplayingDecoder; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * @author wayne 26 | * @version IntegerHeaderFrameDecoderReplay, 2021/8/13 27 | */ 28 | public class IntegerHeaderFrameDecoderReplay extends ReplayingDecoder { 29 | 30 | protected void decode(ChannelHandlerContext ctx, 31 | ByteBuf buf, List out) throws Exception { 32 | 33 | out.add(buf.readBytes(buf.readInt())); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/IntegerHeaderFrameDecoderSteps.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.ReplayingDecoder; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * @author wayne 26 | * @version IntegerHeaderFrameDecoderSteps, 2021/8/13 27 | */ 28 | public class IntegerHeaderFrameDecoderSteps extends ReplayingDecoder { 29 | 30 | private int length; 31 | 32 | public IntegerHeaderFrameDecoderSteps() { 33 | // Set the initial state. 34 | super(MyDecoderState.READ_LENGTH); 35 | } 36 | 37 | @Override 38 | protected void decode(ChannelHandlerContext ctx, 39 | ByteBuf buf, List out) throws Exception { 40 | switch (state()) { 41 | case READ_LENGTH: 42 | length = buf.readInt(); 43 | checkpoint(MyDecoderState.READ_CONTENT); 44 | case READ_CONTENT: 45 | ByteBuf frame = buf.readBytes(length); 46 | checkpoint(MyDecoderState.READ_LENGTH); 47 | out.add(frame); 48 | break; 49 | default: 50 | throw new Error("Shouldn't reach here."); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/IntegerToStringEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.handler.codec.MessageToMessageEncoder; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | * @author wayne 25 | * @version IntegerToStringEncoder, 2021/8/13 26 | */ 27 | public class IntegerToStringEncoder extends 28 | MessageToMessageEncoder { 29 | 30 | @Override 31 | public void encode(ChannelHandlerContext ctx, Integer message, List out) 32 | throws Exception { 33 | out.add(message.toString()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/MyDecoderState.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | /** 19 | * @author wayne 20 | * @version MyDecoderState, 2021/8/13 21 | */ 22 | public enum MyDecoderState { 23 | READ_LENGTH, 24 | READ_CONTENT; 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/SquareDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.handler.codec.ByteToMessageDecoder; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * @author wayne 26 | * @version SquareDecoder, 2021/8/13 27 | */ 28 | public class SquareDecoder extends ByteToMessageDecoder { 29 | @Override 30 | public void decode(ChannelHandlerContext ctx, ByteBuf in, List out) 31 | throws Exception { 32 | out.add(in.readBytes(in.readableBytes())); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/flydean14/custcodec/StringToIntegerDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean14.custcodec; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.handler.codec.MessageToMessageDecoder; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | * @author wayne 25 | * @version StringToIntegerDecoder, 2021/8/13 26 | */ 27 | public class StringToIntegerDecoder extends 28 | MessageToMessageDecoder { 29 | 30 | @Override 31 | public void decode(ChannelHandlerContext ctx, String message, 32 | List out) throws Exception { 33 | out.add(message.length()); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/flydean17/marshalling/MarshallingReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.marshalling; 17 | 18 | import lombok.extern.slf4j.Slf4j; 19 | import org.jboss.marshalling.MarshallerFactory; 20 | import org.jboss.marshalling.Marshalling; 21 | import org.jboss.marshalling.MarshallingConfiguration; 22 | import org.jboss.marshalling.Unmarshaller; 23 | 24 | import java.io.FileInputStream; 25 | import java.io.IOException; 26 | 27 | @Slf4j 28 | public class MarshallingReader { 29 | 30 | public void marshallingRead(String fileName) throws IOException, ClassNotFoundException { 31 | // 使用river协议创建MarshallerFactory 32 | MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("river"); 33 | // 创建配置文件 34 | MarshallingConfiguration configuration = new MarshallingConfiguration(); 35 | // 使用版本号4 36 | configuration.setVersion(4); 37 | final Unmarshaller unmarshaller = marshallerFactory.createUnmarshaller(configuration); 38 | try(FileInputStream is = new FileInputStream(fileName)){ 39 | unmarshaller.start(Marshalling.createByteInput(is)); 40 | Student student=(Student)unmarshaller.readObject(); 41 | log.info("student:{}",student); 42 | unmarshaller.finish(); 43 | } 44 | } 45 | 46 | public static void main(String[] args) throws IOException, ClassNotFoundException { 47 | MarshallingReader reader= new MarshallingReader(); 48 | reader.marshallingRead("/tmp/marshall.txt"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/marshalling/Student.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.marshalling; 17 | 18 | import lombok.AllArgsConstructor; 19 | import lombok.Data; 20 | 21 | import java.io.Serializable; 22 | 23 | @Data 24 | @AllArgsConstructor 25 | public class Student implements Serializable { 26 | 27 | private String name; 28 | private int age; 29 | private String className; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | import io.netty.bootstrap.Bootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioSocketChannel; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | import java.util.List; 26 | 27 | /** 28 | * 发送一个Student的对象到server端 29 | */ 30 | @Slf4j 31 | public final class StudentClient { 32 | 33 | static final String HOST = System.getProperty("host", "127.0.0.1"); 34 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 35 | 36 | public static void main(String[] args) throws Exception { 37 | 38 | EventLoopGroup group = new NioEventLoopGroup(); 39 | try { 40 | Bootstrap b = new Bootstrap(); 41 | b.group(group) 42 | .channel(NioSocketChannel.class) 43 | .handler(new StudentClientInitializer()); 44 | // 建立连接 45 | Channel ch = b.connect(HOST, PORT).sync().channel(); 46 | // 等待关闭 47 | ch.closeFuture().sync(); 48 | } finally { 49 | group.shutdownGracefully(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.SimpleChannelInboundHandler; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | @Slf4j 23 | public class StudentClientHandler extends SimpleChannelInboundHandler { 24 | 25 | @Override 26 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 27 | // channel活跃 28 | //构建一个Student,并将其写入到channel中 29 | Student student= Student.newBuilder().setAge(22).setName("flydean").build(); 30 | log.info("client发送消息{}",student); 31 | ctx.write(student); 32 | ctx.flush(); 33 | } 34 | 35 | @Override 36 | public void channelRead0(ChannelHandlerContext ctx, Student student) throws Exception { 37 | log.info("client收到消息{}",student); 38 | } 39 | 40 | @Override 41 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 42 | // 异常处理 43 | log.error("出现异常",cause); 44 | ctx.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.protobuf.ProtobufDecoder; 22 | import io.netty.handler.codec.protobuf.ProtobufEncoder; 23 | import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 24 | import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 25 | 26 | public class StudentClientInitializer extends ChannelInitializer { 27 | 28 | @Override 29 | public void initChannel(SocketChannel ch) { 30 | ChannelPipeline p = ch.pipeline(); 31 | 32 | p.addLast(new ProtobufVarint32FrameDecoder()); 33 | p.addLast(new ProtobufDecoder(Student.getDefaultInstance())); 34 | 35 | p.addLast(new ProtobufVarint32LengthFieldPrepender()); 36 | p.addLast(new ProtobufEncoder()); 37 | 38 | p.addLast(new StudentClientHandler()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentOrBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | public interface StudentOrBuilder extends 19 | // @@protoc_insertion_point(interface_extends:com.flydean17.protobuf.Student) 20 | com.google.protobuf.MessageOrBuilder { 21 | 22 | /** 23 | * int32 age = 1; 24 | * @return Whether the age field is set. 25 | */ 26 | boolean hasAge(); 27 | /** 28 | * int32 age = 1; 29 | * @return The age. 30 | */ 31 | int getAge(); 32 | 33 | /** 34 | * string name = 2; 35 | * @return Whether the name field is set. 36 | */ 37 | boolean hasName(); 38 | /** 39 | * string name = 2; 40 | * @return The name. 41 | */ 42 | java.lang.String getName(); 43 | /** 44 | * string name = 2; 45 | * @return The bytes for name. 46 | */ 47 | com.google.protobuf.ByteString 48 | getNameBytes(); 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.EventLoopGroup; 20 | import io.netty.channel.nio.NioEventLoopGroup; 21 | import io.netty.channel.socket.nio.NioServerSocketChannel; 22 | import io.netty.handler.logging.LogLevel; 23 | import io.netty.handler.logging.LoggingHandler; 24 | 25 | /** 26 | * student server用来接收student消息 27 | */ 28 | public final class StudentServer { 29 | 30 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 31 | 32 | public static void main(String[] args) throws Exception { 33 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 34 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 35 | try { 36 | ServerBootstrap b = new ServerBootstrap(); 37 | b.group(bossGroup, workerGroup) 38 | .channel(NioServerSocketChannel.class) 39 | .handler(new LoggingHandler(LogLevel.INFO)) 40 | .childHandler(new StudentServerInitializer()); 41 | 42 | b.bind(PORT).sync().channel().closeFuture().sync(); 43 | } finally { 44 | bossGroup.shutdownGracefully(); 45 | workerGroup.shutdownGracefully(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | import io.netty.channel.ChannelFuture; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | @Slf4j 24 | public class StudentServerHandler extends SimpleChannelInboundHandler { 25 | 26 | @Override 27 | public void channelRead0(ChannelHandlerContext ctx, Student student) throws Exception { 28 | log.info("server收到消息{}",student); 29 | // 写入消息 30 | ChannelFuture future = ctx.write(student); 31 | } 32 | 33 | @Override 34 | public void channelReadComplete(ChannelHandlerContext ctx) { 35 | ctx.flush(); 36 | } 37 | 38 | @Override 39 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 40 | // 异常处理 41 | log.error("出现异常",cause); 42 | ctx.close(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/StudentServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean17.protobuf; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.protobuf.ProtobufDecoder; 22 | import io.netty.handler.codec.protobuf.ProtobufEncoder; 23 | import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 24 | import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 25 | 26 | public class StudentServerInitializer extends ChannelInitializer { 27 | 28 | @Override 29 | public void initChannel(SocketChannel ch) throws Exception { 30 | ChannelPipeline p = ch.pipeline(); 31 | 32 | p.addLast(new ProtobufVarint32FrameDecoder()); 33 | p.addLast(new ProtobufDecoder(Student.getDefaultInstance())); 34 | 35 | p.addLast(new ProtobufVarint32LengthFieldPrepender()); 36 | p.addLast(new ProtobufEncoder()); 37 | 38 | p.addLast(new StudentServerHandler()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/flydean17/protobuf/student.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package com.flydean17.protobuf; 4 | 5 | option java_multiple_files = true; 6 | option java_package = "com.flydean17.protobuf"; 7 | //option java_outer_classname = "StudentWrapper"; 8 | 9 | message Student { 10 | optional int32 age = 1; 11 | optional string name =2; 12 | } -------------------------------------------------------------------------------- /src/main/java/com/flydean18/httprequest/HttpRequestServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean18.httprequest; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.ChannelOption; 21 | import io.netty.channel.EventLoopGroup; 22 | import io.netty.channel.nio.NioEventLoopGroup; 23 | import io.netty.channel.socket.nio.NioServerSocketChannel; 24 | import io.netty.handler.logging.LogLevel; 25 | import io.netty.handler.logging.LoggingHandler; 26 | import lombok.extern.slf4j.Slf4j; 27 | 28 | /** 29 | * 一个简单的http server,用来从web端接收http请求 30 | */ 31 | @Slf4j 32 | public final class HttpRequestServer { 33 | 34 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 35 | 36 | public static void main(String[] args) throws Exception { 37 | // server配置 38 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 39 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 40 | try { 41 | ServerBootstrap b = new ServerBootstrap(); 42 | b.option(ChannelOption.SO_BACKLOG, 1024); 43 | b.group(bossGroup, workerGroup) 44 | .channel(NioServerSocketChannel.class) 45 | .handler(new LoggingHandler(LogLevel.INFO)) 46 | .childHandler(new HttpRequestServerInitializer()); 47 | 48 | Channel ch = b.bind(PORT).sync().channel(); 49 | log.info("请打开你的浏览器,访问 http://127.0.0.1:8000/"); 50 | ch.closeFuture().sync(); 51 | } finally { 52 | bossGroup.shutdownGracefully(); 53 | workerGroup.shutdownGracefully(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean18/httprequest/HttpRequestServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean18.httprequest; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpServerCodec; 22 | import io.netty.handler.codec.http.HttpServerExpectContinueHandler; 23 | 24 | public class HttpRequestServerInitializer extends ChannelInitializer { 25 | 26 | @Override 27 | public void initChannel(SocketChannel ch) { 28 | ChannelPipeline p = ch.pipeline(); 29 | p.addLast(new HttpServerCodec()); 30 | p.addLast(new HttpServerExpectContinueHandler()); 31 | p.addLast(new HttpRequestServerHandler()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/flydean19/httpclientrequest/ClientRequestClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean19.httpclientrequest; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpClientCodec; 22 | import io.netty.handler.codec.http.HttpContentDecompressor; 23 | 24 | public class ClientRequestClientInitializer extends ChannelInitializer { 25 | 26 | @Override 27 | public void initChannel(SocketChannel ch) { 28 | ChannelPipeline p = ch.pipeline(); 29 | 30 | p.addLast(new HttpClientCodec()); 31 | p.addLast(new HttpContentDecompressor()); 32 | //p.addLast(new HttpObjectAggregator(1048576)); 33 | p.addLast(new ClientRequestClientHandler()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/flydean19/httpclientrequest/HttpRequestServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean19.httpclientrequest; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import io.netty.handler.logging.LogLevel; 24 | import io.netty.handler.logging.LoggingHandler; 25 | import lombok.extern.slf4j.Slf4j; 26 | 27 | /** 28 | * HTTP 服务器 29 | */ 30 | @Slf4j 31 | public final class HttpRequestServer { 32 | 33 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 34 | 35 | public static void main(String[] args) throws Exception { 36 | // server配置 37 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 38 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 39 | try { 40 | ServerBootstrap b = new ServerBootstrap(); 41 | b.group(bossGroup, workerGroup) 42 | .channel(NioServerSocketChannel.class) 43 | .handler(new LoggingHandler(LogLevel.INFO)) 44 | .childHandler(new HttpRequestServerInitializer()); 45 | 46 | Channel ch = b.bind(PORT).sync().channel(); 47 | 48 | log.info("请打开你的浏览器,访问 http://127.0.0.1:8000/"); 49 | 50 | ch.closeFuture().sync(); 51 | } finally { 52 | bossGroup.shutdownGracefully(); 53 | workerGroup.shutdownGracefully(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean19/httpclientrequest/HttpRequestServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean19.httpclientrequest; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpContentCompressor; 22 | import io.netty.handler.codec.http.HttpRequestDecoder; 23 | import io.netty.handler.codec.http.HttpResponseEncoder; 24 | 25 | public class HttpRequestServerInitializer extends ChannelInitializer { 26 | 27 | @Override 28 | public void initChannel(SocketChannel ch) { 29 | ChannelPipeline p = ch.pipeline(); 30 | 31 | p.addLast(new HttpRequestDecoder()); 32 | //p.addLast(new HttpObjectAggregator(1048576)); 33 | p.addLast(new HttpResponseEncoder()); 34 | // p.addLast(new HttpContentCompressor()); 35 | p.addLast(new HttpRequestServerHandler()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/flydean20/httpfile/HttpFileServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean20.httpfile; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import io.netty.handler.logging.LogLevel; 24 | import io.netty.handler.logging.LoggingHandler; 25 | import lombok.extern.slf4j.Slf4j; 26 | 27 | @Slf4j 28 | public final class HttpFileServer { 29 | 30 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 31 | 32 | public static void main(String[] args) throws Exception { 33 | 34 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 35 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 36 | try { 37 | ServerBootstrap b = new ServerBootstrap(); 38 | b.group(bossGroup, workerGroup) 39 | .channel(NioServerSocketChannel.class) 40 | .handler(new LoggingHandler(LogLevel.INFO)) 41 | .childHandler(new HttpFileServerInitializer()); 42 | 43 | Channel ch = b.bind(PORT).sync().channel(); 44 | 45 | log.info("请打开你的浏览器,访问 http://127.0.0.1:8000/"); 46 | 47 | ch.closeFuture().sync(); 48 | } finally { 49 | bossGroup.shutdownGracefully(); 50 | workerGroup.shutdownGracefully(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/flydean20/httpfile/HttpFileServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean20.httpfile; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpObjectAggregator; 22 | import io.netty.handler.codec.http.HttpServerCodec; 23 | import io.netty.handler.stream.ChunkedWriteHandler; 24 | 25 | public class HttpFileServerInitializer extends ChannelInitializer { 26 | 27 | @Override 28 | public void initChannel(SocketChannel ch) { 29 | ChannelPipeline pipeline = ch.pipeline(); 30 | pipeline.addLast(new HttpServerCodec()); 31 | pipeline.addLast(new HttpObjectAggregator(65536)); 32 | pipeline.addLast(new ChunkedWriteHandler()); 33 | pipeline.addLast(new HttpFileServerHandler()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/flydean21/httpupload/HttpUploadClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean21.httpupload; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpClientCodec; 22 | import io.netty.handler.codec.http.HttpContentDecompressor; 23 | import io.netty.handler.stream.ChunkedWriteHandler; 24 | 25 | public class HttpUploadClientInitializer extends ChannelInitializer { 26 | 27 | @Override 28 | public void initChannel(SocketChannel ch) { 29 | ChannelPipeline pipeline = ch.pipeline(); 30 | 31 | pipeline.addLast("codec", new HttpClientCodec()); 32 | pipeline.addLast("inflater", new HttpContentDecompressor()); 33 | pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); 34 | pipeline.addLast("handler", new HttpUploadClientHandler()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/flydean21/httpupload/HttpUploadServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean21.httpupload; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import io.netty.handler.logging.LogLevel; 24 | import io.netty.handler.logging.LoggingHandler; 25 | import lombok.extern.slf4j.Slf4j; 26 | 27 | /** 28 | * HTTP文件上传服务器 29 | */ 30 | @Slf4j 31 | public final class HttpUploadServer { 32 | 33 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 34 | 35 | public static void main(String[] args) throws Exception { 36 | 37 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 38 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 39 | try { 40 | ServerBootstrap b = new ServerBootstrap(); 41 | b.group(bossGroup, workerGroup); 42 | b.channel(NioServerSocketChannel.class); 43 | b.handler(new LoggingHandler(LogLevel.INFO)); 44 | b.childHandler(new HttpUploadServerInitializer()); 45 | 46 | Channel ch = b.bind(PORT).sync().channel(); 47 | 48 | log.info("请打开你的浏览器,访问 http://127.0.0.1:8000/"); 49 | 50 | ch.closeFuture().sync(); 51 | } finally { 52 | bossGroup.shutdownGracefully(); 53 | workerGroup.shutdownGracefully(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean21/httpupload/HttpUploadServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean21.httpupload; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpContentCompressor; 22 | import io.netty.handler.codec.http.HttpRequestDecoder; 23 | import io.netty.handler.codec.http.HttpResponseEncoder; 24 | 25 | public class HttpUploadServerInitializer extends ChannelInitializer { 26 | 27 | @Override 28 | public void initChannel(SocketChannel ch) { 29 | ChannelPipeline pipeline = ch.pipeline(); 30 | 31 | pipeline.addLast(new HttpRequestDecoder()); 32 | pipeline.addLast(new HttpResponseEncoder()); 33 | pipeline.addLast(new HttpContentCompressor()); 34 | pipeline.addLast(new HttpUploadServerHandler()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/flydean22/cors/CustResponseHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean22.cors; 17 | 18 | import io.netty.buffer.Unpooled; 19 | import io.netty.channel.ChannelFutureListener; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.SimpleChannelInboundHandler; 22 | import io.netty.handler.codec.http.DefaultFullHttpResponse; 23 | import io.netty.handler.codec.http.FullHttpResponse; 24 | import io.netty.handler.codec.http.HttpResponseStatus; 25 | import io.netty.handler.codec.http.HttpVersion; 26 | 27 | /** 28 | * 自定义响应handler 29 | */ 30 | public class CustResponseHandler extends SimpleChannelInboundHandler { 31 | @Override 32 | public void channelRead0(ChannelHandlerContext ctx, Object msg) { 33 | final FullHttpResponse response = new DefaultFullHttpResponse( 34 | HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER); 35 | response.headers().set("site", "www.flydean.com"); 36 | ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/flydean22/cors/HttpCorsServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean22.cors; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.EventLoopGroup; 20 | import io.netty.channel.nio.NioEventLoopGroup; 21 | import io.netty.channel.socket.nio.NioServerSocketChannel; 22 | import io.netty.handler.logging.LogLevel; 23 | import io.netty.handler.logging.LoggingHandler; 24 | 25 | public final class HttpCorsServer { 26 | 27 | static final int PORT = Integer.parseInt(System.getProperty("port","8000")); 28 | 29 | public static void main(String[] args) throws Exception { 30 | 31 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 32 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 33 | try { 34 | ServerBootstrap b = new ServerBootstrap(); 35 | b.group(bossGroup, workerGroup) 36 | .channel(NioServerSocketChannel.class) 37 | .handler(new LoggingHandler(LogLevel.INFO)) 38 | .childHandler(new HttpCorsServerInitializer()); 39 | 40 | b.bind(PORT).sync().channel().closeFuture().sync(); 41 | } finally { 42 | bossGroup.shutdownGracefully(); 43 | workerGroup.shutdownGracefully(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/flydean22/cors/HttpCorsServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean22.cors; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpObjectAggregator; 22 | import io.netty.handler.codec.http.HttpRequestDecoder; 23 | import io.netty.handler.codec.http.HttpResponseEncoder; 24 | import io.netty.handler.codec.http.cors.CorsConfig; 25 | import io.netty.handler.codec.http.cors.CorsConfigBuilder; 26 | import io.netty.handler.codec.http.cors.CorsHandler; 27 | import io.netty.handler.stream.ChunkedWriteHandler; 28 | 29 | public class HttpCorsServerInitializer extends ChannelInitializer { 30 | 31 | @Override 32 | public void initChannel(SocketChannel ch) { 33 | 34 | ChannelPipeline pipeline = ch.pipeline(); 35 | pipeline.addLast(new HttpResponseEncoder()); 36 | pipeline.addLast(new HttpRequestDecoder()); 37 | pipeline.addLast(new HttpObjectAggregator(65536)); 38 | pipeline.addLast(new ChunkedWriteHandler()); 39 | 40 | CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build(); 41 | pipeline.addLast(new CorsHandler(corsConfig)); 42 | 43 | pipeline.addLast(new CustResponseHandler()); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/flydean23/socketserver/TestSocketHttpPage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean23.socketserver; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | import java.io.*; 24 | import java.net.URL; 25 | 26 | /** 27 | * 读取html页面的数据,展示给用户 28 | */ 29 | @Slf4j 30 | public final class TestSocketHttpPage { 31 | 32 | public static ByteBuf getContent() throws IOException { 33 | URL url= TestSocketHttpPage.class.getClassLoader().getResource("socket.html"); 34 | log.info("url: {}",url); 35 | String filePath = url.getFile(); 36 | File file = new File(filePath); 37 | log.info(file.getCanonicalPath()); 38 | FileReader fileReader = new FileReader(file); 39 | BufferedReader reader = new BufferedReader(fileReader); 40 | StringBuilder builder= new StringBuilder(); 41 | reader.lines().forEach(builder::append); 42 | reader.close(); 43 | fileReader.close(); 44 | return Unpooled.copiedBuffer(builder.toString(), CharsetUtil.UTF_8); 45 | } 46 | 47 | private TestSocketHttpPage() { 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/flydean23/socketserver/TestSocketServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean23.socketserver; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | 26 | @Slf4j 27 | public final class TestSocketServer { 28 | 29 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 30 | 31 | public static void main(String[] args) throws Exception { 32 | 33 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 34 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 35 | try { 36 | ServerBootstrap b = new ServerBootstrap(); 37 | b.group(bossGroup, workerGroup) 38 | .channel(NioServerSocketChannel.class) 39 | .childHandler(new TestSocketServerInitializer()); 40 | 41 | Channel ch = b.bind(PORT).sync().channel(); 42 | 43 | log.info("使用你的浏览器访问:" + "http://127.0.0.1:" + PORT + '/'); 44 | 45 | ch.closeFuture().sync(); 46 | } finally { 47 | bossGroup.shutdownGracefully(); 48 | workerGroup.shutdownGracefully(); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/flydean23/socketserver/TestSocketServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean23.socketserver; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpObjectAggregator; 22 | import io.netty.handler.codec.http.HttpServerCodec; 23 | 24 | /** 25 | */ 26 | public class TestSocketServerInitializer extends ChannelInitializer { 27 | 28 | @Override 29 | public void initChannel(SocketChannel ch) throws Exception { 30 | ChannelPipeline pipeline = ch.pipeline(); 31 | 32 | pipeline.addLast(new HttpServerCodec()); 33 | pipeline.addLast(new HttpObjectAggregator(65536)); 34 | pipeline.addLast(new TestSocketServerHandler()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/flydean24/socketserver2/Server2FrameHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean24.socketserver2; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.SimpleChannelInboundHandler; 20 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 21 | import io.netty.handler.codec.http.websocketx.WebSocketFrame; 22 | 23 | import java.util.Locale; 24 | 25 | /** 26 | * 专门处理WebSocketFrame 27 | */ 28 | public class Server2FrameHandler extends SimpleChannelInboundHandler { 29 | 30 | @Override 31 | protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { 32 | 33 | if (frame instanceof TextWebSocketFrame) { 34 | // 将接收到的消息转换成为大写 35 | String request = ((TextWebSocketFrame) frame).text(); 36 | ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.CHINA))); 37 | } else { 38 | String message = "不支持的Frame类型: " + frame.getClass().getName(); 39 | throw new UnsupportedOperationException(message); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/flydean24/socketserver2/Server2HttpPage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean24.socketserver2; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | import java.io.BufferedReader; 24 | import java.io.File; 25 | import java.io.FileReader; 26 | import java.io.IOException; 27 | import java.net.URL; 28 | 29 | @Slf4j 30 | public final class Server2HttpPage { 31 | 32 | public static ByteBuf getContent() throws IOException { 33 | URL url= Server2HttpPage.class.getClassLoader().getResource("socket2.html"); 34 | log.info("url: {}",url); 35 | String filePath = url.getFile(); 36 | File file = new File(filePath); 37 | log.info(file.getCanonicalPath()); 38 | FileReader fileReader = new FileReader(file); 39 | BufferedReader reader = new BufferedReader(fileReader); 40 | StringBuilder builder= new StringBuilder(); 41 | reader.lines().forEach(builder::append); 42 | reader.close(); 43 | fileReader.close(); 44 | return Unpooled.copiedBuffer(builder.toString(), CharsetUtil.UTF_8); 45 | } 46 | 47 | private Server2HttpPage() { 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/flydean24/socketserver2/Server2Initializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean24.socketserver2; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.http.HttpObjectAggregator; 22 | import io.netty.handler.codec.http.HttpServerCodec; 23 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 24 | import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; 25 | 26 | /** 27 | */ 28 | public class Server2Initializer extends ChannelInitializer { 29 | 30 | private static final String WEBSOCKET_PATH = "/websocket"; 31 | 32 | @Override 33 | public void initChannel(SocketChannel ch) throws Exception { 34 | ChannelPipeline pipeline = ch.pipeline(); 35 | 36 | pipeline.addLast(new HttpServerCodec()); 37 | pipeline.addLast(new HttpObjectAggregator(65536)); 38 | pipeline.addLast(new WebSocketServerCompressionHandler()); 39 | pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); 40 | pipeline.addLast(new Server2HttpHandler()); 41 | pipeline.addLast(new Server2FrameHandler()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/flydean24/socketserver2/Server2Server.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean24.socketserver2; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import io.netty.handler.logging.LogLevel; 24 | import io.netty.handler.logging.LoggingHandler; 25 | import lombok.extern.slf4j.Slf4j; 26 | 27 | @Slf4j 28 | public final class Server2Server { 29 | 30 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 31 | 32 | public static void main(String[] args) throws Exception { 33 | 34 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 35 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 36 | try { 37 | ServerBootstrap b = new ServerBootstrap(); 38 | b.group(bossGroup, workerGroup) 39 | .channel(NioServerSocketChannel.class) 40 | .handler(new LoggingHandler(LogLevel.INFO)) 41 | .childHandler(new Server2Initializer()); 42 | 43 | Channel ch = b.bind(PORT).sync().channel(); 44 | 45 | log.info("使用你的浏览器访问:" + "http://127.0.0.1:" + PORT + '/'); 46 | 47 | ch.closeFuture().sync(); 48 | } finally { 49 | bossGroup.shutdownGracefully(); 50 | workerGroup.shutdownGracefully(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/flydean26/http2server/CustHttp2HandlerBuilder.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright 2022 learn-netty4 Project 4 | * 5 | * The learn-netty4 Project licenses this file to you under the Apache License, 6 | * version 2.0 (the "License"); you may not use this file except in compliance 7 | * with the License. You may obtain a copy of the License at: 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * License for the specific language governing permissions and limitations 15 | * under the License. 16 | */ 17 | package com.flydean26.http2server; 18 | 19 | import io.netty.handler.codec.http2.*; 20 | 21 | import static io.netty.handler.logging.LogLevel.INFO; 22 | 23 | public final class CustHttp2HandlerBuilder 24 | extends AbstractHttp2ConnectionHandlerBuilder { 25 | 26 | private static final Http2FrameLogger logger = new Http2FrameLogger(INFO, CustHttp2Handler.class); 27 | 28 | public CustHttp2HandlerBuilder() { 29 | frameLogger(logger); 30 | } 31 | 32 | @Override 33 | public CustHttp2Handler build() { 34 | return super.build(); 35 | } 36 | 37 | @Override 38 | protected CustHttp2Handler build(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, 39 | Http2Settings initialSettings) { 40 | CustHttp2Handler handler = new CustHttp2Handler(decoder, encoder, initialSettings); 41 | frameListener(handler); 42 | return handler; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/flydean26/http2server/CustProtocolNegotiationHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean26.http2server; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.handler.codec.http.HttpObjectAggregator; 20 | import io.netty.handler.codec.http.HttpServerCodec; 21 | import io.netty.handler.ssl.ApplicationProtocolNames; 22 | import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; 23 | 24 | /** 25 | * 自定义的ProtocolNegotiationHandler,根据传入的protocol不同,使用不同的HTTP handler 26 | */ 27 | public class CustProtocolNegotiationHandler extends ApplicationProtocolNegotiationHandler { 28 | 29 | private static final int MAX_CONTENT_LENGTH = 1024 * 100; 30 | 31 | protected CustProtocolNegotiationHandler() { 32 | super(ApplicationProtocolNames.HTTP_1_1); 33 | } 34 | 35 | @Override 36 | protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { 37 | if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { 38 | ctx.pipeline().addLast(new CustHttp2HandlerBuilder().build()); 39 | return; 40 | } 41 | 42 | if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { 43 | ctx.pipeline().addLast(new HttpServerCodec(), 44 | new HttpObjectAggregator(MAX_CONTENT_LENGTH), 45 | new CustHttp1Handler("使用ALPN协议")); 46 | return; 47 | } 48 | 49 | throw new IllegalStateException("未知协议: " + protocol); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/flydean30/http2client/CustHttp2SettingsHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean30.http2client; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.ChannelPromise; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import io.netty.handler.codec.http2.Http2Settings; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | import java.util.concurrent.TimeUnit; 25 | 26 | /** 27 | * 处理 Http2Setting 28 | */ 29 | @Slf4j 30 | public class CustHttp2SettingsHandler extends SimpleChannelInboundHandler { 31 | private final ChannelPromise promise; 32 | 33 | public CustHttp2SettingsHandler(ChannelPromise promise) { 34 | this.promise = promise; 35 | } 36 | 37 | /** 38 | * 等待设置完毕 39 | */ 40 | public void awaitSettings(long timeout, TimeUnit unit){ 41 | if (!promise.awaitUninterruptibly(timeout, unit)) { 42 | throw new IllegalStateException("设置时间超时"); 43 | } 44 | if (!promise.isSuccess()) { 45 | throw new RuntimeException(promise.cause()); 46 | } 47 | } 48 | 49 | @Override 50 | protected void channelRead0(ChannelHandlerContext ctx, Http2Settings msg) throws Exception { 51 | log.info("接收到Http2Settings消息:{}",msg); 52 | promise.setSuccess(); 53 | //处理完毕,删除handler 54 | ctx.pipeline().remove(this); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean31/http2framecodecserver/CustProtocolNegotiationHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean31.http2framecodecserver; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.handler.codec.http.HttpObjectAggregator; 20 | import io.netty.handler.codec.http.HttpServerCodec; 21 | import io.netty.handler.codec.http2.Http2FrameCodecBuilder; 22 | import io.netty.handler.ssl.ApplicationProtocolNames; 23 | import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; 24 | 25 | /** 26 | * 自定义的ProtocolNegotiationHandler,根据传入的protocol不同,使用不同的HTTP handler 27 | */ 28 | public class CustProtocolNegotiationHandler extends ApplicationProtocolNegotiationHandler { 29 | 30 | private static final int MAX_CONTENT_LENGTH = 1024 * 100; 31 | 32 | protected CustProtocolNegotiationHandler() { 33 | super(ApplicationProtocolNames.HTTP_1_1); 34 | } 35 | 36 | @Override 37 | protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { 38 | if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { 39 | ctx.pipeline().addLast(Http2FrameCodecBuilder.forServer().build(), new CustHttp2Handler()); 40 | return; 41 | } 42 | 43 | if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { 44 | ctx.pipeline().addLast(new HttpServerCodec(), 45 | new HttpObjectAggregator(MAX_CONTENT_LENGTH), 46 | new CustHttp1Handler("使用ALPN协议")); 47 | return; 48 | } 49 | 50 | throw new IllegalStateException("未知协议: " + protocol); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean34/http2images/ImageServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean34.http2images; 17 | 18 | import io.netty.channel.EventLoopGroup; 19 | import io.netty.channel.nio.NioEventLoopGroup; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | /** 23 | * 一个同时支持HTTP和HTTP2的image服务器 24 | */ 25 | @Slf4j 26 | public final class ImageServer { 27 | 28 | public static void main(String[] args) throws Exception { 29 | EventLoopGroup group = new NioEventLoopGroup(); 30 | ImageHttp2Server http2 = new ImageHttp2Server(group); 31 | ImageHttp1Server http = new ImageHttp1Server(group); 32 | try { 33 | http2.start(); 34 | log.info("使用你的浏览器访问: " + "http://127.0.0.1:" + ImageHttp1Server.PORT); 35 | http.start().sync(); 36 | } finally { 37 | group.shutdownGracefully(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/flydean35/proxy/SimpleDumpProxyInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean35.proxy; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.socket.SocketChannel; 20 | import io.netty.handler.logging.LogLevel; 21 | import io.netty.handler.logging.LoggingHandler; 22 | 23 | public class SimpleDumpProxyInitializer extends ChannelInitializer { 24 | 25 | private final String remoteHost; 26 | private final int remotePort; 27 | 28 | public SimpleDumpProxyInitializer(String remoteHost, int remotePort) { 29 | this.remoteHost = remoteHost; 30 | this.remotePort = remotePort; 31 | } 32 | 33 | @Override 34 | public void initChannel(SocketChannel ch) { 35 | ch.pipeline().addLast( 36 | new LoggingHandler(LogLevel.INFO), 37 | new SimpleDumpProxyInboundHandler(remoteHost, remotePort)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/flydean35/proxy/SimpleDumpProxyOutboundHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean35.proxy; 17 | 18 | import io.netty.channel.*; 19 | import lombok.extern.slf4j.Slf4j; 20 | 21 | @Slf4j 22 | public class SimpleDumpProxyOutboundHandler extends ChannelInboundHandlerAdapter { 23 | 24 | private final Channel inboundChannel; 25 | 26 | public SimpleDumpProxyOutboundHandler(Channel inboundChannel) { 27 | this.inboundChannel = inboundChannel; 28 | } 29 | 30 | @Override 31 | public void channelActive(ChannelHandlerContext ctx) { 32 | ctx.read(); 33 | } 34 | 35 | @Override 36 | public void channelRead(final ChannelHandlerContext ctx, Object msg) { 37 | // 将outboundChannel中的消息读取,并写入到inboundChannel中 38 | inboundChannel.writeAndFlush(msg).addListener((ChannelFutureListener) future -> { 39 | if (future.isSuccess()) { 40 | ctx.channel().read(); 41 | } else { 42 | future.channel().close(); 43 | } 44 | }); 45 | } 46 | 47 | @Override 48 | public void channelInactive(ChannelHandlerContext ctx) { 49 | SimpleDumpProxyInboundHandler.closeOnFlush(inboundChannel); 50 | } 51 | 52 | @Override 53 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 54 | // 异常处理 55 | log.error("出现异常",cause); 56 | SimpleDumpProxyInboundHandler.closeOnFlush(ctx.channel()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/flydean36/socksproxy/ClientPromiseHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean36.socksproxy; 17 | 18 | import io.netty.channel.Channel; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import io.netty.util.concurrent.Promise; 22 | 23 | public final class ClientPromiseHandler extends ChannelInboundHandlerAdapter { 24 | 25 | private final Promise promise; 26 | 27 | public ClientPromiseHandler(Promise promise) { 28 | this.promise = promise; 29 | } 30 | 31 | @Override 32 | public void channelActive(ChannelHandlerContext ctx) { 33 | ctx.pipeline().remove(this); 34 | promise.setSuccess(ctx.channel()); 35 | } 36 | 37 | @Override 38 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { 39 | promise.setFailure(throwable); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/flydean36/socksproxy/RelayHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean36.socksproxy; 17 | 18 | import io.netty.buffer.Unpooled; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.ChannelFutureListener; 21 | import io.netty.channel.ChannelHandlerContext; 22 | import io.netty.channel.ChannelInboundHandlerAdapter; 23 | import io.netty.util.ReferenceCountUtil; 24 | import lombok.extern.slf4j.Slf4j; 25 | 26 | @Slf4j 27 | public final class RelayHandler extends ChannelInboundHandlerAdapter { 28 | 29 | private final Channel relayChannel; 30 | 31 | public RelayHandler(Channel relayChannel) { 32 | this.relayChannel = relayChannel; 33 | } 34 | 35 | @Override 36 | public void channelActive(ChannelHandlerContext ctx) { 37 | ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); 38 | } 39 | 40 | @Override 41 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 42 | if (relayChannel.isActive()) { 43 | relayChannel.writeAndFlush(msg); 44 | } else { 45 | ReferenceCountUtil.release(msg); 46 | } 47 | } 48 | 49 | @Override 50 | public void channelInactive(ChannelHandlerContext ctx) { 51 | if (relayChannel.isActive()) { 52 | relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); 53 | } 54 | } 55 | 56 | @Override 57 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 58 | log.error(cause.getMessage(),cause); 59 | ctx.close(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/flydean36/socksproxy/SocksServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean36.socksproxy; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.EventLoopGroup; 20 | import io.netty.channel.nio.NioEventLoopGroup; 21 | import io.netty.channel.socket.nio.NioServerSocketChannel; 22 | import io.netty.handler.logging.LogLevel; 23 | import io.netty.handler.logging.LoggingHandler; 24 | 25 | public final class SocksServer { 26 | 27 | static final int PORT = 1080; 28 | 29 | public static void main(String[] args) throws Exception { 30 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 31 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 32 | try { 33 | ServerBootstrap b = new ServerBootstrap(); 34 | b.group(bossGroup, workerGroup) 35 | .channel(NioServerSocketChannel.class) 36 | .handler(new LoggingHandler(LogLevel.INFO)) 37 | .childHandler(new SocksServerInitializer()); 38 | b.bind(PORT).sync().channel().closeFuture().sync(); 39 | } finally { 40 | bossGroup.shutdownGracefully(); 41 | workerGroup.shutdownGracefully(); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/flydean36/socksproxy/SocksServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean36.socksproxy; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.socket.SocketChannel; 20 | import io.netty.handler.codec.socksx.SocksPortUnificationServerHandler; 21 | import io.netty.handler.logging.LogLevel; 22 | import io.netty.handler.logging.LoggingHandler; 23 | 24 | public final class SocksServerInitializer extends ChannelInitializer { 25 | @Override 26 | public void initChannel(SocketChannel ch) throws Exception { 27 | ch.pipeline().addLast( 28 | new LoggingHandler(LogLevel.DEBUG), 29 | new SocksPortUnificationServerHandler(), 30 | SocksServerHandler.INSTANCE); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/flydean40/udtByte/UDTByteEchoClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean40.udtByte; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.SimpleChannelInboundHandler; 22 | import io.netty.channel.udt.nio.NioUdtProvider; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | import java.nio.charset.StandardCharsets; 26 | 27 | /** 28 | * 客户端处理器 29 | */ 30 | @Slf4j 31 | public class UDTByteEchoClientHandler extends SimpleChannelInboundHandler { 32 | 33 | private final ByteBuf message; 34 | 35 | public UDTByteEchoClientHandler() { 36 | super(false); 37 | message = Unpooled.buffer(UDTByteEchoClient.SIZE); 38 | message.writeBytes("www.flydean.com".getBytes(StandardCharsets.UTF_8)); 39 | } 40 | 41 | @Override 42 | public void channelActive(final ChannelHandlerContext ctx) { 43 | log.info("channel active {}" , NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); 44 | ctx.writeAndFlush(message); 45 | } 46 | 47 | @Override 48 | public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { 49 | ctx.write(msg); 50 | } 51 | 52 | @Override 53 | public void channelReadComplete(ChannelHandlerContext ctx) { 54 | ctx.flush(); 55 | } 56 | 57 | @Override 58 | public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { 59 | log.error(cause.getMessage(),cause); 60 | ctx.close(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/flydean40/udtByte/UDTByteEchoServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean40.udtByte; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import io.netty.channel.udt.nio.NioUdtProvider; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | /** 25 | * 服务端的处理器 26 | */ 27 | @Sharable 28 | @Slf4j 29 | public class UDTByteEchoServerHandler extends ChannelInboundHandlerAdapter { 30 | 31 | @Override 32 | public void channelActive(final ChannelHandlerContext ctx) { 33 | log.info("UDT handler active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); 34 | } 35 | 36 | @Override 37 | public void channelRead(final ChannelHandlerContext ctx, Object msg) { 38 | ctx.write(msg); 39 | } 40 | 41 | @Override 42 | public void channelReadComplete(ChannelHandlerContext ctx) { 43 | ctx.flush(); 44 | } 45 | 46 | @Override 47 | public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { 48 | log.error(cause.getMessage(),cause); 49 | ctx.close(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/flydean41/udtMessage/UDTMsgEchoServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean41.udtMessage; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import io.netty.channel.udt.nio.NioUdtProvider; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | /** 25 | * UDT message 服务器端处理器 26 | */ 27 | @Sharable 28 | @Slf4j 29 | public class UDTMsgEchoServerHandler extends ChannelInboundHandlerAdapter { 30 | 31 | @Override 32 | public void channelActive(final ChannelHandlerContext ctx) { 33 | log.info("ECHO active {}" , NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); 34 | } 35 | 36 | @Override 37 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 38 | ctx.write(msg); 39 | } 40 | 41 | @Override 42 | public void channelReadComplete(ChannelHandlerContext ctx) { 43 | ctx.flush(); 44 | } 45 | 46 | @Override 47 | public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { 48 | log.error(cause.getMessage(),cause); 49 | ctx.close(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/flydean42/udtRendezvous/UDTByteHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean42.udtRendezvous; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.SimpleChannelInboundHandler; 22 | import io.netty.channel.udt.nio.NioUdtProvider; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | import java.nio.charset.StandardCharsets; 26 | 27 | @Slf4j 28 | public class UDTByteHandler extends SimpleChannelInboundHandler { 29 | 30 | private final ByteBuf message; 31 | 32 | public UDTByteHandler(final int messageSize) { 33 | super(false); 34 | message = Unpooled.buffer(messageSize); 35 | message.writeBytes("www.flydean.com".getBytes(StandardCharsets.UTF_8)); 36 | } 37 | 38 | @Override 39 | public void channelActive(ChannelHandlerContext ctx) { 40 | log.info("ECHO active {}" ,NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); 41 | ctx.writeAndFlush(message); 42 | } 43 | 44 | @Override 45 | public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) { 46 | ctx.write(buf); 47 | } 48 | 49 | @Override 50 | public void channelReadComplete(ChannelHandlerContext ctx) { 51 | ctx.flush(); 52 | } 53 | 54 | @Override 55 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 56 | log.error(cause.getMessage(),cause); 57 | ctx.close(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/flydean42/udtRendezvous/UDTByteRendezvousOne.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean42.udtRendezvous; 17 | 18 | import io.netty.util.internal.SocketUtils; 19 | 20 | import java.net.InetSocketAddress; 21 | import java.net.SocketAddress; 22 | 23 | public class UDTByteRendezvousOne extends UDTByteRendezvousBase { 24 | 25 | public UDTByteRendezvousOne(int messageSize, SocketAddress myAddress, SocketAddress peerAddress) { 26 | super(messageSize, myAddress, peerAddress); 27 | } 28 | 29 | public static void main(String[] args) throws Exception { 30 | final int messageSize = 64 * 1024; 31 | final InetSocketAddress myAddress = SocketUtils.socketAddress("127.0.0.1", 8000); 32 | final InetSocketAddress peerAddress = SocketUtils.socketAddress("127.0.0.1", 8001); 33 | new UDTByteRendezvousOne(messageSize, myAddress, peerAddress).run(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/flydean42/udtRendezvous/UDTByteRendezvousTwo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean42.udtRendezvous; 17 | 18 | import io.netty.util.internal.SocketUtils; 19 | 20 | import java.net.InetSocketAddress; 21 | import java.net.SocketAddress; 22 | 23 | 24 | public class UDTByteRendezvousTwo extends UDTByteRendezvousBase { 25 | 26 | public UDTByteRendezvousTwo(int messageSize, SocketAddress myAddress, SocketAddress peerAddress) { 27 | super(messageSize, myAddress, peerAddress); 28 | } 29 | 30 | public static void main(String[] args) throws Exception { 31 | final int messageSize = 64 * 1024; 32 | final InetSocketAddress myAddress = SocketUtils.socketAddress("127.0.0.1", 8001); 33 | final InetSocketAddress peerAddress = SocketUtils.socketAddress("127.0.0.1", 8000); 34 | new UDTByteRendezvousTwo(messageSize, myAddress, peerAddress).run(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/flydean42/udtRendezvous/UDTMsgHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean42.udtRendezvous; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.SimpleChannelInboundHandler; 22 | import io.netty.channel.udt.UdtMessage; 23 | import io.netty.channel.udt.nio.NioUdtProvider; 24 | import lombok.extern.slf4j.Slf4j; 25 | 26 | import java.nio.charset.StandardCharsets; 27 | 28 | @Slf4j 29 | public class UDTMsgHandler extends SimpleChannelInboundHandler { 30 | 31 | private final UdtMessage message; 32 | 33 | public UDTMsgHandler(final int messageSize) { 34 | super(false); 35 | final ByteBuf byteBuf = Unpooled.buffer(messageSize); 36 | byteBuf.writeBytes("www.flydean.com".getBytes(StandardCharsets.UTF_8)); 37 | message = new UdtMessage(byteBuf); 38 | } 39 | 40 | @Override 41 | public void channelActive(final ChannelHandlerContext ctx) { 42 | log.info("ECHO active {}", NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); 43 | ctx.writeAndFlush(message); 44 | } 45 | 46 | @Override 47 | public void channelRead0(ChannelHandlerContext ctx, UdtMessage message) { 48 | ctx.write(message); 49 | } 50 | 51 | @Override 52 | public void channelReadComplete(ChannelHandlerContext ctx) { 53 | ctx.flush(); 54 | } 55 | 56 | @Override 57 | public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { 58 | log.error(cause.getMessage(),cause); 59 | ctx.close(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/flydean42/udtRendezvous/UDTMsgRendezvousOne.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean42.udtRendezvous; 17 | 18 | import io.netty.util.internal.SocketUtils; 19 | 20 | import java.net.InetSocketAddress; 21 | 22 | 23 | public class UDTMsgRendezvousOne extends UDTMsgRendezvousBase { 24 | 25 | public UDTMsgRendezvousOne(final InetSocketAddress self, final InetSocketAddress peer, final int messageSize) { 26 | super(self, peer, messageSize); 27 | } 28 | 29 | public static void main(final String[] args) throws Exception { 30 | final int messageSize = 64 * 1024; 31 | final InetSocketAddress self = SocketUtils.socketAddress("127.0.0.1", 8000); 32 | final InetSocketAddress peer = SocketUtils.socketAddress("127.0.0.1", 8001); 33 | new UDTMsgRendezvousOne(self, peer, messageSize).run(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/flydean42/udtRendezvous/UDTMsgRendezvousTwo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean42.udtRendezvous; 17 | 18 | import io.netty.util.internal.SocketUtils; 19 | 20 | import java.net.InetSocketAddress; 21 | 22 | public class UDTMsgRendezvousTwo extends UDTMsgRendezvousBase { 23 | 24 | public UDTMsgRendezvousTwo(final InetSocketAddress self, final InetSocketAddress peer, final int messageSize) { 25 | super(self, peer, messageSize); 26 | } 27 | 28 | public static void main(final String[] args) throws Exception { 29 | final int messageSize = 64 * 1024; 30 | final InetSocketAddress self = SocketUtils.socketAddress("127.0.0.1", 8001); 31 | final InetSocketAddress peer = SocketUtils.socketAddress("127.0.0.1", 8000); 32 | new UDTMsgRendezvousTwo(self, peer, messageSize).run(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/flydean43/byteBufRef/ByteBufRef.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean43.byteBufRef; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.util.IllegalReferenceCountException; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | import static io.netty.buffer.Unpooled.directBuffer; 23 | 24 | @Slf4j 25 | public class ByteBufRef { 26 | 27 | public static void main(String[] args) { 28 | 29 | ByteBuf buf = directBuffer(); 30 | assert buf.refCnt() == 1; 31 | 32 | boolean destroyed = buf.release(); 33 | assert destroyed; 34 | assert buf.refCnt() == 0; 35 | 36 | try { 37 | buf.writeByte(10); 38 | } catch (IllegalReferenceCountException e) { 39 | log.error(e.getMessage(),e); 40 | } 41 | 42 | 43 | // buf.retain(); 44 | // assert buf.refCnt() == 1; 45 | 46 | buf = directBuffer(); 47 | buf.retain(); 48 | assert buf.refCnt() == 2; 49 | 50 | buf = directBuffer(); 51 | ByteBuf derived = buf.duplicate(); 52 | assert buf.refCnt() == 1; 53 | assert derived.refCnt() == 1; 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean44/tfo/TFOClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean44.tfo; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | import java.nio.charset.StandardCharsets; 24 | 25 | /** 26 | * TFO client 处理器 27 | */ 28 | @Slf4j 29 | public class TFOClientHandler extends ChannelInboundHandlerAdapter { 30 | 31 | private ByteBuf content; 32 | private ChannelHandlerContext ctx; 33 | 34 | @Override 35 | public void channelActive(ChannelHandlerContext ctx) { 36 | this.ctx = ctx; 37 | content = ctx.alloc().directBuffer(256).writeBytes("Hello flydean.com".getBytes(StandardCharsets.UTF_8)); 38 | // 发送消息 39 | sayHello(); 40 | } 41 | 42 | @Override 43 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 44 | // 异常处理 45 | log.error("出现异常",cause); 46 | ctx.close(); 47 | } 48 | 49 | private void sayHello() { 50 | // 向服务器输出消息 51 | ctx.writeAndFlush(content.retain()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/flydean44/tfo/TFOServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean44.tfo; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import io.netty.util.ReferenceCountUtil; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | /** 25 | * @author wayne 26 | * @version TFOServer, 2021/8/1 27 | */ 28 | @Slf4j 29 | public class TFOServerHandler extends ChannelInboundHandlerAdapter { 30 | @Override 31 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 32 | // 对消息进行处理 33 | ByteBuf in = (ByteBuf) msg; 34 | try { 35 | log.info("收到消息:{}",in.toString(io.netty.util.CharsetUtil.US_ASCII)); 36 | }finally { 37 | ReferenceCountUtil.release(msg); 38 | } 39 | 40 | // try { 41 | // // 消息处理 42 | // } finally { 43 | // ReferenceCountUtil.release(msg); 44 | // } 45 | } 46 | 47 | @Override 48 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 49 | // 异常处理 50 | log.error("出现异常",cause); 51 | ctx.close(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/flydean49/extendEnum/Programmer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean49.extendEnum; 17 | 18 | public class Programmer { 19 | 20 | Programmer(int type, String desc){ 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/flydean49/extendEnum/StatusEnum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean49.extendEnum; 17 | 18 | import lombok.Data; 19 | 20 | public enum StatusEnum { 21 | START(1,"start"), 22 | INPROCESS(2,"inprocess"), 23 | END(3,"end"); 24 | 25 | private int code; 26 | private String desc; 27 | 28 | StatusEnum(int code, String desc){ 29 | this.code=code; 30 | this.desc=desc; 31 | } 32 | 33 | public static void main(String[] args) { 34 | StatusEnum start = START; 35 | System.out.println(start.name()); 36 | System.out.println(start.ordinal()); 37 | System.out.println(start.code); 38 | System.out.println(start.desc); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/flydean49/extendEnum/SumEnum.java: -------------------------------------------------------------------------------- 1 | package com.flydean49.extendEnum; 2 | 3 | //public enum SumEnum extends StatusEnum{ 4 | //} 5 | -------------------------------------------------------------------------------- /src/main/java/com/flydean51/affinity/AffinityServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.flydean51.affinity; 2 | /* 3 | * Copyright 2022 learn-netty4 Project 4 | * 5 | * The learn-netty4 Project licenses this file to you under the Apache License, 6 | * version 2.0 (the "License"); you may not use this file except in compliance 7 | * with the License. You may obtain a copy of the License at: 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * License for the specific language governing permissions and limitations 15 | * under the License. 16 | */ 17 | import io.netty.buffer.ByteBuf; 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.channel.ChannelInboundHandlerAdapter; 20 | import io.netty.util.ReferenceCountUtil; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | /** 24 | * @author wayne 25 | * @version AffinityServerHandler, 2021/8/1 26 | */ 27 | @Slf4j 28 | public class AffinityServerHandler extends ChannelInboundHandlerAdapter { 29 | @Override 30 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 31 | // 对消息进行处理 32 | ByteBuf in = (ByteBuf) msg; 33 | try { 34 | log.info("收到消息:{}",in.toString(io.netty.util.CharsetUtil.US_ASCII)); 35 | }finally { 36 | ReferenceCountUtil.release(msg); 37 | } 38 | } 39 | 40 | @Override 41 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 42 | // 异常处理 43 | log.error("出现异常",cause); 44 | ctx.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/epoll/NativeChatClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.epoll; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | /** 24 | * 客户端处理器 25 | */ 26 | @Sharable 27 | @Slf4j 28 | public class NativeChatClientHandler extends SimpleChannelInboundHandler { 29 | 30 | @Override 31 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 32 | log.info("client accepted channel: {}", ctx.channel()); 33 | log.info("接收到消息:{}",msg); 34 | } 35 | 36 | @Override 37 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 38 | // 异常处理 39 | log.error("出现异常",cause); 40 | ctx.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/epoll/NativeChatClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.epoll; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | 26 | /** 27 | * 客户端ChannelPipeline的配置 28 | */ 29 | public class NativeChatClientInitializer extends ChannelInitializer { 30 | 31 | private static final StringDecoder DECODER = new StringDecoder(); 32 | private static final StringEncoder ENCODER = new StringEncoder(); 33 | 34 | private static final NativeChatClientHandler CLIENT_HANDLER = new NativeChatClientHandler(); 35 | 36 | @Override 37 | public void initChannel(SocketChannel ch) { 38 | ChannelPipeline pipeline = ch.pipeline(); 39 | 40 | // 添加行分割器 41 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 42 | pipeline.addLast(DECODER); 43 | pipeline.addLast(ENCODER); 44 | 45 | // 添加客户端处理器 46 | pipeline.addLast(CLIENT_HANDLER); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/epoll/NativeChatServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.epoll; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.Channel; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.epoll.EpollEventLoopGroup; 22 | import io.netty.channel.epoll.EpollServerSocketChannel; 23 | import io.netty.channel.kqueue.KQueueEventLoopGroup; 24 | import io.netty.channel.kqueue.KQueueServerSocketChannel; 25 | import io.netty.handler.logging.LogLevel; 26 | import io.netty.handler.logging.LoggingHandler; 27 | import lombok.extern.slf4j.Slf4j; 28 | 29 | /** 30 | * native chat server 服务器 31 | */ 32 | @Slf4j 33 | public final class NativeChatServer { 34 | 35 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 36 | 37 | public static void main(String[] args) throws Exception { 38 | 39 | EventLoopGroup bossGroup = new EpollEventLoopGroup(1); 40 | EventLoopGroup workerGroup = new EpollEventLoopGroup(); 41 | try { 42 | ServerBootstrap b = new ServerBootstrap(); 43 | b.group(bossGroup, workerGroup) 44 | .channel(EpollServerSocketChannel.class) 45 | .handler(new LoggingHandler(LogLevel.INFO)) 46 | .childHandler(new NativeChatServerInitializer()); 47 | 48 | Channel channel = b.bind(PORT).sync().channel(); 49 | log.info("server channel:{}", channel); 50 | channel.closeFuture().sync(); 51 | } finally { 52 | bossGroup.shutdownGracefully(); 53 | workerGroup.shutdownGracefully(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/epoll/NativeChatServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.epoll; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | 26 | /** 27 | * 初始化一个ChannelPipeline 28 | */ 29 | public class NativeChatServerInitializer extends ChannelInitializer { 30 | 31 | private static final StringDecoder DECODER = new StringDecoder(); 32 | private static final StringEncoder ENCODER = new StringEncoder(); 33 | 34 | private static final NativeChatServerHandler SERVER_HANDLER = new NativeChatServerHandler(); 35 | 36 | @Override 37 | public void initChannel(SocketChannel ch) throws Exception { 38 | ChannelPipeline pipeline = ch.pipeline(); 39 | // 添加行分割器 40 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 41 | // 添加String Decoder和String Encoder,用来进行字符串的转换 42 | pipeline.addLast(DECODER); 43 | pipeline.addLast(ENCODER); 44 | // 最后添加真正的处理器 45 | pipeline.addLast(SERVER_HANDLER); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/kqueue/NativeChatClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.kqueue; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | /** 24 | * 客户端处理器 25 | */ 26 | @Sharable 27 | @Slf4j 28 | public class NativeChatClientHandler extends SimpleChannelInboundHandler { 29 | 30 | @Override 31 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 32 | log.info("client accepted channel: {}", ctx.channel()); 33 | log.info("接收到消息:{}",msg); 34 | } 35 | 36 | @Override 37 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 38 | // 异常处理 39 | log.error("出现异常",cause); 40 | ctx.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/kqueue/NativeChatClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.kqueue; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | 26 | /** 27 | * 客户端ChannelPipeline的配置 28 | */ 29 | public class NativeChatClientInitializer extends ChannelInitializer { 30 | 31 | private static final StringDecoder DECODER = new StringDecoder(); 32 | private static final StringEncoder ENCODER = new StringEncoder(); 33 | 34 | private static final NativeChatClientHandler CLIENT_HANDLER = new NativeChatClientHandler(); 35 | 36 | @Override 37 | public void initChannel(SocketChannel ch) { 38 | ChannelPipeline pipeline = ch.pipeline(); 39 | 40 | // 添加行分割器 41 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 42 | pipeline.addLast(DECODER); 43 | pipeline.addLast(ENCODER); 44 | 45 | // 添加客户端处理器 46 | pipeline.addLast(CLIENT_HANDLER); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/kqueue/NativeChatServer.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright 2022 learn-netty4 Project 4 | * 5 | * The learn-netty4 Project licenses this file to you under the Apache License, 6 | * version 2.0 (the "License"); you may not use this file except in compliance 7 | * with the License. You may obtain a copy of the License at: 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * License for the specific language governing permissions and limitations 15 | * under the License. 16 | */ 17 | package com.flydean52.nativetransport.kqueue; 18 | 19 | import io.netty.bootstrap.ServerBootstrap; 20 | import io.netty.channel.Channel; 21 | import io.netty.channel.EventLoopGroup; 22 | import io.netty.channel.kqueue.KQueueEventLoopGroup; 23 | import io.netty.channel.kqueue.KQueueServerSocketChannel; 24 | import io.netty.handler.logging.LogLevel; 25 | import io.netty.handler.logging.LoggingHandler; 26 | import lombok.extern.slf4j.Slf4j; 27 | 28 | /** 29 | * native chat server 服务器 30 | */ 31 | @Slf4j 32 | public final class NativeChatServer { 33 | 34 | static final int PORT = Integer.parseInt(System.getProperty("port", "8000")); 35 | 36 | public static void main(String[] args) throws Exception { 37 | 38 | EventLoopGroup bossGroup = new KQueueEventLoopGroup(1); 39 | EventLoopGroup workerGroup = new KQueueEventLoopGroup(); 40 | try { 41 | ServerBootstrap b = new ServerBootstrap(); 42 | b.group(bossGroup, workerGroup) 43 | .channel(KQueueServerSocketChannel.class) 44 | .handler(new LoggingHandler(LogLevel.INFO)) 45 | .childHandler(new NativeChatServerInitializer()); 46 | 47 | Channel channel = b.bind(PORT).sync().channel(); 48 | log.info("server channel:{}", channel); 49 | channel.closeFuture().sync(); 50 | } finally { 51 | bossGroup.shutdownGracefully(); 52 | workerGroup.shutdownGracefully(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/flydean52/nativetransport/kqueue/NativeChatServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean52.nativetransport.kqueue; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 22 | import io.netty.handler.codec.Delimiters; 23 | import io.netty.handler.codec.string.StringDecoder; 24 | import io.netty.handler.codec.string.StringEncoder; 25 | 26 | /** 27 | * 初始化一个ChannelPipeline 28 | */ 29 | public class NativeChatServerInitializer extends ChannelInitializer { 30 | 31 | private static final StringDecoder DECODER = new StringDecoder(); 32 | private static final StringEncoder ENCODER = new StringEncoder(); 33 | 34 | private static final NativeChatServerHandler SERVER_HANDLER = new NativeChatServerHandler(); 35 | 36 | @Override 37 | public void initChannel(SocketChannel ch) throws Exception { 38 | ChannelPipeline pipeline = ch.pipeline(); 39 | // 添加行分割器 40 | pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 41 | // 添加String Decoder和String Encoder,用来进行字符串的转换 42 | pipeline.addLast(DECODER); 43 | pipeline.addLast(ENCODER); 44 | // 最后添加真正的处理器 45 | pipeline.addLast(SERVER_HANDLER); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/flydean54/dnstcp/Do53TcpChannelInboundHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean54.dnstcp; 17 | 18 | import io.netty.buffer.ByteBufUtil; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import io.netty.handler.codec.dns.*; 22 | import io.netty.util.NetUtil; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | @Slf4j 26 | class Do53TcpChannelInboundHandler extends SimpleChannelInboundHandler { 27 | @Override 28 | protected void channelRead0(ChannelHandlerContext ctx, DefaultDnsResponse msg) { 29 | try { 30 | readMsg(msg); 31 | } finally { 32 | ctx.close(); 33 | } 34 | } 35 | 36 | private static void readMsg(DefaultDnsResponse msg) { 37 | if (msg.count(DnsSection.QUESTION) > 0) { 38 | DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0); 39 | log.info("question is :{}",question); 40 | } 41 | int i = 0, count = msg.count(DnsSection.ANSWER); 42 | while (i < count) { 43 | DnsRecord record = msg.recordAt(DnsSection.ANSWER, i); 44 | //A记录用来指定主机名或者域名对应的IP地址 45 | if (record.type() == DnsRecordType.A) { 46 | DnsRawRecord raw = (DnsRawRecord) record; 47 | log.info("ip address is: {}",NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content()))); 48 | } 49 | i++; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean54/dnstcp/Do53TcpChannelInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean54.dnstcp; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.dns.TcpDnsQueryEncoder; 22 | import io.netty.handler.codec.dns.TcpDnsResponseDecoder; 23 | 24 | public class Do53TcpChannelInitializer extends ChannelInitializer { 25 | @Override 26 | protected void initChannel(SocketChannel ch) { 27 | ChannelPipeline p = ch.pipeline(); 28 | p.addLast(new TcpDnsQueryEncoder()) 29 | .addLast(new TcpDnsResponseDecoder()) 30 | .addLast(new Do53TcpChannelInboundHandler()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/flydean55/dnsudp/Do53UdpChannelInboundHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean55.dnsudp; 17 | 18 | import io.netty.buffer.ByteBufUtil; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import io.netty.handler.codec.dns.*; 22 | import io.netty.util.NetUtil; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | @Slf4j 26 | class Do53UdpChannelInboundHandler extends SimpleChannelInboundHandler { 27 | @Override 28 | protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsResponse msg) { 29 | try { 30 | readMsg(msg); 31 | } finally { 32 | ctx.close(); 33 | } 34 | } 35 | 36 | private static void readMsg(DatagramDnsResponse msg) { 37 | if (msg.count(DnsSection.QUESTION) > 0) { 38 | DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0); 39 | log.info("question is :{}", question); 40 | } 41 | int i = 0, count = msg.count(DnsSection.ANSWER); 42 | while (i < count) { 43 | DnsRecord record = msg.recordAt(DnsSection.ANSWER, i); 44 | if (record.type() == DnsRecordType.A) { 45 | //A记录用来指定主机名或者域名对应的IP地址 46 | DnsRawRecord raw = (DnsRawRecord) record; 47 | log.info("ip address is: {}",NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content()))); 48 | } 49 | i++; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean55/dnsudp/Do53UdpChannelInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean55.dnsudp; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.DatagramChannel; 21 | import io.netty.handler.codec.dns.DatagramDnsQueryEncoder; 22 | import io.netty.handler.codec.dns.DatagramDnsResponseDecoder; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | @Slf4j 26 | class Do53UdpChannelInitializer extends ChannelInitializer { 27 | @Override 28 | protected void initChannel(DatagramChannel ch) throws Exception { 29 | ChannelPipeline p = ch.pipeline(); 30 | p.addLast(new DatagramDnsQueryEncoder()) 31 | .addLast(new DatagramDnsResponseDecoder()) 32 | .addLast(new Do53UdpChannelInboundHandler()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/flydean56/dnsdot/DotChannelInboundHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean56.dnsdot; 17 | 18 | import io.netty.buffer.ByteBufUtil; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import io.netty.handler.codec.dns.*; 22 | import io.netty.util.NetUtil; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | @Slf4j 26 | class DotChannelInboundHandler extends SimpleChannelInboundHandler { 27 | @Override 28 | protected void channelRead0(ChannelHandlerContext ctx, DefaultDnsResponse msg) { 29 | try { 30 | readMsg(msg); 31 | } finally { 32 | ctx.close(); 33 | } 34 | } 35 | 36 | private static void readMsg(DefaultDnsResponse msg) { 37 | if (msg.count(DnsSection.QUESTION) > 0) { 38 | DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0); 39 | log.info("question is :{}", question); 40 | } 41 | int i = 0, count = msg.count(DnsSection.ANSWER); 42 | while (i < count) { 43 | DnsRecord record = msg.recordAt(DnsSection.ANSWER, i); 44 | if (record.type() == DnsRecordType.A) { 45 | //A记录用来指定主机名或者域名对应的IP地址 46 | DnsRawRecord raw = (DnsRawRecord) record; 47 | log.info("ip address is: {}",NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content()))); 48 | } 49 | i++; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean56/dnsdot/DotChannelInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean56.dnsdot; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.dns.TcpDnsQueryEncoder; 22 | import io.netty.handler.codec.dns.TcpDnsResponseDecoder; 23 | import io.netty.handler.ssl.SslContext; 24 | 25 | class DotChannelInitializer extends ChannelInitializer { 26 | private final SslContext sslContext; 27 | private final String dnsServer; 28 | private final int dnsPort; 29 | 30 | public DotChannelInitializer(SslContext sslContext, String dnsServer, int dnsPort) { 31 | this.sslContext = sslContext; 32 | this.dnsServer = dnsServer; 33 | this.dnsPort = dnsPort; 34 | } 35 | 36 | @Override 37 | protected void initChannel(SocketChannel ch) { 38 | ChannelPipeline p = ch.pipeline(); 39 | p.addLast(sslContext.newHandler(ch.alloc(), dnsServer, dnsPort)) 40 | .addLast(new TcpDnsQueryEncoder()) 41 | .addLast(new TcpDnsResponseDecoder()) 42 | .addLast(new DotChannelInboundHandler()); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/flydean57/dnsserver/Do53ServerChannelInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean57.dnsserver; 17 | 18 | import io.netty.channel.Channel; 19 | import io.netty.channel.ChannelInitializer; 20 | import io.netty.handler.codec.dns.*; 21 | 22 | class Do53ServerChannelInitializer extends ChannelInitializer { 23 | @Override 24 | protected void initChannel(Channel ch) throws Exception { 25 | ch.pipeline().addLast( 26 | new TcpDnsQueryDecoder(), 27 | new TcpDnsResponseEncoder(), 28 | new Do53ServerInboundHandler()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/flydean57/dnsserver/Do53ServerInboundHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean57.dnsserver; 17 | 18 | import io.netty.buffer.Unpooled; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.SimpleChannelInboundHandler; 21 | import io.netty.handler.codec.dns.*; 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | @Slf4j 25 | class Do53ServerInboundHandler extends SimpleChannelInboundHandler { 26 | 27 | private static final byte[] QUERY_RESULT = new byte[]{46, 53, 107, 110}; 28 | 29 | @Override 30 | protected void channelRead0(ChannelHandlerContext ctx, 31 | DnsQuery msg) throws Exception { 32 | DnsQuestion question = msg.recordAt(DnsSection.QUESTION); 33 | log.info("Query is: {}", question); 34 | ctx.writeAndFlush(newResponse(msg, question, 1000, QUERY_RESULT)); 35 | } 36 | 37 | private DefaultDnsResponse newResponse(DnsQuery query, 38 | DnsQuestion question, 39 | long ttl, byte[]... addresses) { 40 | DefaultDnsResponse response = new DefaultDnsResponse(query.id()); 41 | response.addRecord(DnsSection.QUESTION, question); 42 | 43 | for (byte[] address : addresses) { 44 | DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord( 45 | question.name(), 46 | DnsRecordType.A, ttl, Unpooled.wrappedBuffer(address)); 47 | response.addRecord(DnsSection.ANSWER, queryAnswer); 48 | } 49 | return response; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/flydean57/dnsserver/Do53TcpServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean57.dnsserver; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.*; 20 | import io.netty.channel.nio.NioEventLoopGroup; 21 | import io.netty.channel.socket.nio.NioServerSocketChannel; 22 | import io.netty.handler.logging.LogLevel; 23 | import io.netty.handler.logging.LoggingHandler; 24 | 25 | public final class Do53TcpServer { 26 | 27 | public static void main(String[] args) throws Exception { 28 | int dnsServerPort = 53; 29 | startServer(dnsServerPort); 30 | } 31 | 32 | private static void startServer(int dnsServerPort) throws InterruptedException { 33 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 34 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 35 | ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, 36 | workerGroup) 37 | .channel(NioServerSocketChannel.class) 38 | .handler(new LoggingHandler(LogLevel.INFO)) 39 | .childHandler(new Do53ServerChannelInitializer()); 40 | final Channel channel = bootstrap.bind(dnsServerPort).channel(); 41 | channel.closeFuture().sync(); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/flydean58/proxyprotocol/ClientHander.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean58.proxyprotocol; 17 | 18 | import io.netty.channel.*; 19 | import io.netty.handler.codec.haproxy.HAProxyMessage; 20 | import io.netty.handler.codec.haproxy.HAProxyMessageEncoder; 21 | 22 | public class ClientHander extends ChannelOutboundHandlerAdapter { 23 | 24 | @Override 25 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 26 | ctx.pipeline().addBefore(ctx.name(), null, HAProxyMessageEncoder.INSTANCE); 27 | super.handlerAdded(ctx); 28 | } 29 | 30 | @Override 31 | public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { 32 | ChannelFuture future1 = ctx.write(msg, promise); 33 | if (msg instanceof HAProxyMessage) { 34 | future1.addListener((ChannelFutureListener) future2 -> { 35 | if (future2.isSuccess()) { 36 | ctx.pipeline().remove(HAProxyMessageEncoder.INSTANCE); 37 | ctx.pipeline().remove(ClientHander.this); 38 | } else { 39 | ctx.close(); 40 | } 41 | }); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/flydean58/proxyprotocol/ProxyProtocolServer.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright 2022 learn-netty4 Project 4 | * 5 | * The learn-netty4 Project licenses this file to you under the Apache License, 6 | * version 2.0 (the "License"); you may not use this file except in compliance 7 | * with the License. You may obtain a copy of the License at: 8 | * 9 | * https://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * License for the specific language governing permissions and limitations 15 | * under the License. 16 | */ 17 | package com.flydean58.proxyprotocol; 18 | 19 | import io.netty.bootstrap.ServerBootstrap; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioServerSocketChannel; 23 | import io.netty.handler.logging.LogLevel; 24 | import io.netty.handler.logging.LoggingHandler; 25 | 26 | public final class ProxyProtocolServer { 27 | 28 | public static void main(String[] args) throws Exception { 29 | int port= 8080; 30 | startServer(port); 31 | } 32 | 33 | private static void startServer(int port) throws InterruptedException { 34 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 35 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 36 | try { 37 | ServerBootstrap b = new ServerBootstrap(); 38 | b.group(bossGroup, workerGroup) 39 | .channel(NioServerSocketChannel.class) 40 | .handler(new LoggingHandler(LogLevel.INFO)) 41 | .childHandler(new ServerInitializer()); 42 | b.bind(port).sync().channel().closeFuture().sync(); 43 | } finally { 44 | bossGroup.shutdownGracefully(); 45 | workerGroup.shutdownGracefully(); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/flydean58/proxyprotocol/ServerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean58.proxyprotocol; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.ByteBufUtil; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.ChannelInitializer; 22 | import io.netty.channel.SimpleChannelInboundHandler; 23 | import io.netty.channel.socket.SocketChannel; 24 | import io.netty.handler.codec.haproxy.HAProxyMessage; 25 | import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; 26 | import io.netty.handler.logging.LogLevel; 27 | import io.netty.handler.logging.LoggingHandler; 28 | import lombok.extern.slf4j.Slf4j; 29 | 30 | @Slf4j 31 | class ServerInitializer extends ChannelInitializer { 32 | @Override 33 | public void initChannel(SocketChannel ch) throws Exception { 34 | ch.pipeline().addLast( 35 | new LoggingHandler(LogLevel.DEBUG), 36 | new HAProxyMessageDecoder(), 37 | new SimpleChannelInboundHandler() { 38 | @Override 39 | protected void channelRead0(ChannelHandlerContext ctx, Object msg) { 40 | if (msg instanceof HAProxyMessage) { 41 | log.info("proxy message is : {}", msg); 42 | } else if (msg instanceof ByteBuf) { 43 | log.info("bytebuf message is : {}", ByteBufUtil.prettyHexDump((ByteBuf) msg)); 44 | } 45 | } 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/flydean59/sctp/SctpChatClientHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean59.sctp; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.ChannelInboundHandlerAdapter; 22 | import io.netty.channel.sctp.SctpMessage; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | 26 | @Slf4j 27 | public class SctpChatClientHandler extends ChannelInboundHandlerAdapter { 28 | 29 | private final ByteBuf firstMessage; 30 | 31 | public SctpChatClientHandler() { 32 | firstMessage = Unpooled.buffer(256); 33 | for (int i = 0; i < firstMessage.capacity(); i++) { 34 | firstMessage.writeByte((byte) i); 35 | } 36 | } 37 | 38 | @Override 39 | public void channelActive(ChannelHandlerContext ctx) { 40 | ctx.writeAndFlush(new SctpMessage(0, 0, firstMessage)); 41 | } 42 | 43 | @Override 44 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 45 | ctx.write(msg); 46 | } 47 | 48 | @Override 49 | public void channelReadComplete(ChannelHandlerContext ctx) { 50 | ctx.flush(); 51 | } 52 | 53 | @Override 54 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 55 | log.error("SctpChatClientHandler exception:{}", cause.getMessage()); 56 | ctx.close(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/flydean59/sctp/SctpChatServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean59.sctp; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | import io.netty.channel.ChannelHandlerContext; 20 | import io.netty.channel.ChannelInboundHandlerAdapter; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | @Sharable 24 | @Slf4j 25 | public class SctpChatServerHandler extends ChannelInboundHandlerAdapter { 26 | 27 | @Override 28 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 29 | ctx.write(msg); 30 | } 31 | 32 | @Override 33 | public void channelReadComplete(ChannelHandlerContext ctx) { 34 | ctx.flush(); 35 | } 36 | 37 | @Override 38 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 39 | log.error("SctpChatServerHandler exception:{}",cause.getMessage()); 40 | ctx.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/flydean61/memcached/MemcachedInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean61.memcached; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.memcache.binary.BinaryMemcacheClientCodec; 22 | import io.netty.handler.codec.memcache.binary.BinaryMemcacheObjectAggregator; 23 | 24 | class MemcachedInitializer extends ChannelInitializer { 25 | @Override 26 | protected void initChannel(SocketChannel ch) { 27 | ChannelPipeline p = ch.pipeline(); 28 | p.addLast(new BinaryMemcacheClientCodec()); 29 | p.addLast(new BinaryMemcacheObjectAggregator(Integer.MAX_VALUE)); 30 | p.addLast(new MemcachedClientHandler()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/flydean62/redis/RedisChannelInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean62.redis; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.redis.RedisArrayAggregator; 22 | import io.netty.handler.codec.redis.RedisBulkStringAggregator; 23 | import io.netty.handler.codec.redis.RedisDecoder; 24 | import io.netty.handler.codec.redis.RedisEncoder; 25 | 26 | class RedisChannelInitializer extends ChannelInitializer { 27 | @Override 28 | protected void initChannel(SocketChannel ch) { 29 | ChannelPipeline p = ch.pipeline(); 30 | p.addLast(new RedisDecoder()); 31 | p.addLast(new RedisBulkStringAggregator()); 32 | p.addLast(new RedisArrayAggregator()); 33 | p.addLast(new RedisEncoder()); 34 | p.addLast(new RedisClientHandler()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/flydean64/mqttbroker/MqttCustBroker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean64.mqttbroker; 17 | 18 | import io.netty.bootstrap.ServerBootstrap; 19 | import io.netty.channel.ChannelFuture; 20 | import io.netty.channel.ChannelOption; 21 | import io.netty.channel.EventLoopGroup; 22 | import io.netty.channel.nio.NioEventLoopGroup; 23 | import io.netty.channel.socket.nio.NioServerSocketChannel; 24 | import lombok.extern.slf4j.Slf4j; 25 | 26 | @Slf4j 27 | public final class MqttCustBroker { 28 | 29 | public static void main(String[] args) throws Exception { 30 | startBroker(); 31 | } 32 | 33 | private static void startBroker() throws InterruptedException { 34 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 35 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 36 | 37 | try { 38 | ServerBootstrap b = new ServerBootstrap(); 39 | b.group(bossGroup, workerGroup); 40 | b.option(ChannelOption.SO_BACKLOG, 1024); 41 | b.channel(NioServerSocketChannel.class); 42 | b.childHandler(new MqttCustBrokerInitializer()); 43 | 44 | ChannelFuture f = b.bind(1883).sync(); 45 | f.channel().closeFuture().sync(); 46 | } finally { 47 | workerGroup.shutdownGracefully(); 48 | bossGroup.shutdownGracefully(); 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/flydean64/mqttbroker/MqttCustBrokerInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package com.flydean64.mqttbroker; 18 | 19 | import io.netty.channel.ChannelInitializer; 20 | import io.netty.channel.socket.SocketChannel; 21 | import io.netty.handler.codec.mqtt.MqttDecoder; 22 | import io.netty.handler.codec.mqtt.MqttEncoder; 23 | import io.netty.handler.timeout.IdleStateHandler; 24 | 25 | import java.util.concurrent.TimeUnit; 26 | 27 | class MqttCustBrokerInitializer extends ChannelInitializer { 28 | protected void initChannel(SocketChannel ch) throws Exception { 29 | ch.pipeline().addLast(MqttEncoder.INSTANCE); 30 | ch.pipeline().addLast(new MqttDecoder()); 31 | ch.pipeline().addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS)); 32 | ch.pipeline().addLast(new MqttCustBrokerHandler()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/flydean65/mqttclient/MqttClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean65.mqttclient; 17 | 18 | import io.netty.bootstrap.Bootstrap; 19 | import io.netty.channel.ChannelFuture; 20 | import io.netty.channel.EventLoopGroup; 21 | import io.netty.channel.nio.NioEventLoopGroup; 22 | import io.netty.channel.socket.nio.NioSocketChannel; 23 | 24 | public final class MqttClient { 25 | 26 | public static void main(String[] args) throws Exception { 27 | String brokerHost = "127.0.0.1"; 28 | int hostPort = 1883; 29 | String clientId = "clientId"; 30 | String userName = "jack"; 31 | String password = "ma"; 32 | startClient(brokerHost, hostPort, clientId, userName, password); 33 | } 34 | 35 | private static void startClient(String brokerHost, int hostPort, String clientId, String userName, String password) throws InterruptedException { 36 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 37 | try { 38 | Bootstrap b = new Bootstrap(); 39 | b.group(workerGroup); 40 | b.channel(NioSocketChannel.class); 41 | b.handler(new MqttClientChannelInitializer(clientId, userName, password)); 42 | 43 | ChannelFuture f = b.connect(brokerHost, hostPort).sync(); 44 | f.channel().closeFuture().sync(); 45 | } finally { 46 | workerGroup.shutdownGracefully(); 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/flydean65/mqttclient/MqttClientChannelInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean65.mqttclient; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.socket.SocketChannel; 20 | import io.netty.handler.codec.mqtt.MqttDecoder; 21 | import io.netty.handler.codec.mqtt.MqttEncoder; 22 | import io.netty.handler.timeout.IdleStateHandler; 23 | import lombok.AllArgsConstructor; 24 | 25 | import java.util.concurrent.TimeUnit; 26 | 27 | @AllArgsConstructor 28 | class MqttClientChannelInitializer extends ChannelInitializer { 29 | private final String clientId; 30 | private final String userName; 31 | private final String password; 32 | 33 | protected void initChannel(SocketChannel ch) { 34 | ch.pipeline().addLast( MqttEncoder.INSTANCE); 35 | ch.pipeline().addLast(new MqttDecoder()); 36 | ch.pipeline().addLast(new IdleStateHandler(0, 30, 0, TimeUnit.SECONDS)); 37 | ch.pipeline().addLast(new MqttClientHandler(clientId, userName, password)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/flydean68/ocspstapling/SHA1DigestCalculator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 learn-netty4 Project 3 | * 4 | * The learn-netty4 Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package com.flydean68.ocspstapling; 17 | 18 | import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; 19 | import org.bouncycastle.asn1.x509.AlgorithmIdentifier; 20 | import org.bouncycastle.crypto.digests.SHA1Digest; 21 | import org.bouncycastle.operator.DigestCalculator; 22 | 23 | import java.io.ByteArrayOutputStream; 24 | import java.io.OutputStream; 25 | 26 | /** 27 | * 从BcX509ExtensionUtils中拷贝的SHA1DigestCalculator 28 | */ 29 | public class SHA1DigestCalculator implements DigestCalculator { 30 | private ByteArrayOutputStream bOut; 31 | 32 | public SHA1DigestCalculator() { 33 | this.bOut = new ByteArrayOutputStream(); 34 | } 35 | 36 | public AlgorithmIdentifier getAlgorithmIdentifier() { 37 | return new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1); 38 | } 39 | 40 | public OutputStream getOutputStream() { 41 | return this.bOut; 42 | } 43 | 44 | public byte[] getDigest() { 45 | byte[] var1 = this.bOut.toByteArray(); 46 | this.bOut.reset(); 47 | SHA1Digest var2 = new SHA1Digest(); 48 | var2.update(var1, 0, var1.length); 49 | byte[] var3 = new byte[var2.getDigestSize()]; 50 | var2.doFinal(var3, 0); 51 | return var3; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/image.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Netty平铺图片测试 4 | 5 | 6 | 7 | 这里我们展示2*3的图片


8 |

9 |
10 |
11 |
12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/img0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/src/main/resources/com/flydean34/http2images/img0.jpg -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/img1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/src/main/resources/com/flydean34/http2images/img1.jpg -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/img2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/src/main/resources/com/flydean34/http2images/img2.jpg -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/img3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/src/main/resources/com/flydean34/http2images/img3.jpg -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/img4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/src/main/resources/com/flydean34/http2images/img4.jpg -------------------------------------------------------------------------------- /src/main/resources/com/flydean34/http2images/img5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ddean2009/learn-netty4/bc6419881b6bb281732d31ee31c046a4371756a4/src/main/resources/com/flydean34/http2images/img5.jpg -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/socket2.html: -------------------------------------------------------------------------------- 1 | 分离websocket处理器 2 | 3 | 35 |
36 | 38 |

输出:

39 | 40 |
41 | 42 | 43 | --------------------------------------------------------------------------------