1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.demo.netty;
19
20 import java.io.File;
21 import java.nio.channels.spi.SelectorProvider;
22 import java.util.concurrent.Executor;
23
24 import org.newsclub.net.unix.AFSocketAddress;
25 import org.newsclub.net.unix.AFUNIXSelectorProvider;
26 import org.newsclub.net.unix.AFUNIXSocketAddress;
27
28 import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;
29
30 import io.netty.bootstrap.ServerBootstrap;
31 import io.netty.channel.ChannelFuture;
32 import io.netty.channel.ChannelInitializer;
33 import io.netty.channel.ChannelOption;
34 import io.netty.channel.EventLoopGroup;
35 import io.netty.channel.nio.NioEventLoopGroup;
36 import io.netty.channel.socket.SocketChannel;
37 import io.netty.channel.socket.nio.NioServerSocketChannel;
38
39
40
41
42
43
44
45 @SuppressWarnings("FutureReturnValueIgnored" )
46 public class EchoServer {
47 private final AFSocketAddress addr;
48
49 public EchoServer(AFSocketAddress addr) {
50 this.addr = addr;
51 }
52
53 public void run() throws Exception {
54 SelectorProvider provider = AFUNIXSelectorProvider.provider();
55
56
57
58 EventLoopGroup bossGroup = new NioEventLoopGroup(0, (Executor) null, provider);
59 EventLoopGroup workerGroup = new NioEventLoopGroup(0, (Executor) null, provider);
60 try {
61 ServerBootstrap b = new ServerBootstrap();
62 b.group(bossGroup, workerGroup)
63 .channelFactory(() -> new NioServerSocketChannel(provider))
64 .childHandler(new ChannelInitializer<SocketChannel>() {
65 @Override
66 public void initChannel(SocketChannel ch) throws Exception {
67 ch.pipeline().addLast(new EchoServerHandler());
68 }
69 })
70 .option(ChannelOption.SO_BACKLOG, 128)
71 .childOption(ChannelOption.SO_KEEPALIVE, true);
72
73
74 ChannelFuture f = b.bind(addr).sync();
75
76
77
78
79 f.channel().closeFuture().sync();
80 } finally {
81 workerGroup.shutdownGracefully();
82 bossGroup.shutdownGracefully();
83 }
84 }
85
86 @SuppressFBWarnings("PATH_TRAVERSAL_IN")
87 public static void main(String[] args) throws Exception {
88 File path = new File("/tmp/nettyecho");
89 if (args.length > 0) {
90 path = new File(args[0]);
91 }
92
93 AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(path);
94 System.out.println("Binding to " + addr);
95
96 new EchoServer(addr).run();
97
98 }
99 }