Netty simple TCP server

Moki Lv6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package pl.org.moki;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Application {

private static final Logger logger = LogManager.getLogger();

public static void main(String[] args) throws Exception {
int port = 80;
logger.info("Server starting");

EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new ProxyChannelHandler());
}
})
.childOption(ChannelOption.SO_KEEPALIVE, true);

ChannelFuture f = b.bind(port).sync();
if (f.isSuccess())
logger.info("Server started successfully");
f.channel().closeFuture().sync();

} finally {
logger.info("Server closing");

workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();

logger.info("Server closed successfully");
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package pl.org.moki;

import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;

public class ProxyChannelHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println(ctx.channel().remoteAddress() + ": Channel Active");
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object o) throws Exception {
String s = (String) o;
System.out.println(ctx.channel().remoteAddress() + ": " + s);
ctx.channel().writeAndFlush("Thanks\n");
}

@Override
public void channelInactive(ChannelHandlerContext ctx) {
System.out.println(ctx.channel().remoteAddress() + ": Channel Inactive");
}

}
On this page
Netty simple TCP server