├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src └── main └── java ├── Main.java ├── NettyClient.java ├── NettyHandler.java ├── NettyServer.java └── ServerFlow.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | *.iml 11 | 12 | .idea/ 13 | .target/ 14 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 15 | hs_err_pid* 16 | target/* 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Netty Two Way TCP Client Server 2 | Sample code, on how to use Netty to build a simple TCP Server/Client, Exchanging string messages. 3 | Since I don't find a simple example on the internet, 4 | and to practice using Netty, i have this code snippet. Feel free to modify and reuse. 5 | 6 | I had a lot of help from Atomix guys ! 7 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | netty-sample 8 | netty-sample 9 | 1.0-SNAPSHOT 10 | 11 | 12 | io.netty 13 | netty-all 14 | 4.1.6.Final 15 | 16 | 17 | org.projectlombok 18 | lombok 19 | 1.16.12 20 | provided 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | import io.netty.buffer.Unpooled; 2 | import io.netty.channel.ChannelFuture; 3 | 4 | public class Main { 5 | public static void main(String[] args) throws Exception{ 6 | if(args.length == 1){ 7 | ServerFlow.OpenServerPort(12000).channel().closeFuture().sync(); 8 | } 9 | else{ 10 | try { 11 | NettyClient nettyClient = new NettyClient(12000); 12 | ChannelFuture channelFuture = nettyClient.connectLoop(); 13 | Thread.sleep(5000); 14 | if (channelFuture.isSuccess()) { 15 | channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("Hello\r\n".getBytes())); 16 | } 17 | } 18 | catch(Exception e){ 19 | System.out.println(e.getMessage()); 20 | System.out.println("Try Starting Server First !!"); 21 | } 22 | finally { 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/NettyClient.java: -------------------------------------------------------------------------------- 1 | import io.netty.bootstrap.Bootstrap; 2 | import io.netty.channel.*; 3 | import io.netty.channel.nio.NioEventLoopGroup; 4 | import io.netty.channel.socket.SocketChannel; 5 | import io.netty.channel.socket.nio.NioSocketChannel; 6 | 7 | public class NettyClient { 8 | int port; 9 | Channel channel; 10 | EventLoopGroup workGroup = new NioEventLoopGroup(); 11 | 12 | public NettyClient(int port){ 13 | this.port = port; 14 | } 15 | 16 | public ChannelFuture connectLoop() throws Exception { 17 | try{ 18 | Bootstrap b = new Bootstrap(); 19 | b.group(workGroup); 20 | b.channel(NioSocketChannel.class); 21 | b.option(ChannelOption.SO_KEEPALIVE, true); 22 | b.handler(new ChannelInitializer() { 23 | protected void initChannel(SocketChannel socketChannel) throws Exception { 24 | socketChannel.pipeline().addLast(new NettyHandler()); 25 | } 26 | }); 27 | ChannelFuture channelFuture = b.connect("127.0.0.1", this.port).sync(); 28 | this.channel = channelFuture.channel(); 29 | 30 | return channelFuture; 31 | }finally{ 32 | } 33 | } 34 | public void shutdown(){ 35 | workGroup.shutdownGracefully(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/NettyHandler.java: -------------------------------------------------------------------------------- 1 | import io.netty.buffer.ByteBuf; 2 | import io.netty.buffer.Unpooled; 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.ChannelInboundHandlerAdapter; 5 | 6 | import java.nio.charset.Charset; 7 | 8 | public class NettyHandler extends ChannelInboundHandlerAdapter { 9 | @Override 10 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 11 | super.channelReadComplete(ctx); 12 | } 13 | 14 | @Override 15 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 16 | ByteBuf byteBuf = (ByteBuf) msg; 17 | String message = byteBuf.toString(Charset.defaultCharset()); 18 | System.out.println("Received Message : " + message); 19 | if(message.equalsIgnoreCase("Hello\r\n")){ 20 | ctx.writeAndFlush(Unpooled.wrappedBuffer("Hello There\r\n".getBytes())); 21 | } 22 | if(message.equalsIgnoreCase("Hello There\r\n")){ 23 | ctx.writeAndFlush(Unpooled.wrappedBuffer("Thanks For Reply !!\r\n".getBytes())); 24 | } 25 | } 26 | 27 | @Override 28 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 29 | super.channelActive(ctx); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/NettyServer.java: -------------------------------------------------------------------------------- 1 | import io.netty.bootstrap.ServerBootstrap; 2 | import io.netty.channel.*; 3 | import io.netty.channel.nio.NioEventLoopGroup; 4 | import io.netty.channel.socket.SocketChannel; 5 | import io.netty.channel.socket.nio.NioServerSocketChannel; 6 | import lombok.Getter; 7 | 8 | public class NettyServer { 9 | int port; 10 | 11 | @Getter 12 | Channel channel; 13 | 14 | @Getter 15 | ChannelFuture channelFuture; 16 | 17 | EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) 18 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 19 | 20 | public NettyServer(int port){ 21 | this.port = port; 22 | } 23 | 24 | public void connectLoop() throws Exception{ 25 | try { 26 | ServerBootstrap b = new ServerBootstrap(); // (2) 27 | b.group(bossGroup, workerGroup) 28 | .channel(NioServerSocketChannel.class) // (3) 29 | .childHandler(new ChannelInitializer() { // (4) 30 | @Override 31 | public void initChannel(SocketChannel ch) throws Exception { 32 | ch.pipeline().addLast(new NettyHandler()); 33 | } 34 | }) 35 | .option(ChannelOption.SO_BACKLOG, 128) // (5) 36 | .childOption(ChannelOption.SO_KEEPALIVE, true); // (6) 37 | 38 | // Bind and start to accept incoming connections. 39 | ChannelFuture f = b.bind(port).sync(); // (7) 40 | 41 | 42 | this.channel = f.channel(); 43 | this.channelFuture = f; 44 | //f.channel().closeFuture().sync(); 45 | } 46 | catch(Exception e) { 47 | System.out.println("Exception in server thread"); 48 | }finally { 49 | 50 | } 51 | } 52 | public void shutdown(){ 53 | workerGroup.shutdownGracefully(); 54 | bossGroup.shutdownGracefully(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/ServerFlow.java: -------------------------------------------------------------------------------- 1 | import io.netty.channel.ChannelFuture; 2 | 3 | public class ServerFlow { 4 | public static ChannelFuture OpenServerPort(int port) { 5 | try { 6 | NettyServer nettyServer = new NettyServer(port); 7 | nettyServer.connectLoop(); 8 | return nettyServer.getChannelFuture(); 9 | } catch (Exception e) { 10 | } 11 | return null; 12 | } 13 | } --------------------------------------------------------------------------------