1 package org.kuali.ole.sip2.service;
2
3 import io.netty.bootstrap.ServerBootstrap;
4 import io.netty.channel.ChannelFuture;
5 import io.netty.channel.ChannelInitializer;
6 import io.netty.channel.ChannelOption;
7 import io.netty.channel.EventLoopGroup;
8 import io.netty.channel.nio.NioEventLoopGroup;
9 import io.netty.channel.socket.SocketChannel;
10 import io.netty.channel.socket.nio.NioServerSocketChannel;
11 import org.apache.log4j.Logger;
12 import org.kuali.ole.sip2.sip2Server.NettyServerHandler;
13
14
15
16
17 public class NettyServer implements Runnable {
18
19 protected int serverPort = 7052;
20 protected boolean isStopped = false;
21 protected Thread runningThread = null;
22 protected String serverUrl = null;
23 private String message;
24 private static final Logger LOG = Logger.getLogger(NettyServer.class);
25 EventLoopGroup bossGroup = new NioEventLoopGroup();
26 EventLoopGroup workerGroup = new NioEventLoopGroup();
27 ChannelFuture f = null;
28
29 public NettyServer() {
30 }
31
32 public NettyServer(int port, String serverUrl) {
33 this.serverPort = port;
34 this.serverUrl = serverUrl;
35 }
36
37 public void run() {
38 synchronized (this) {
39 this.runningThread = Thread.currentThread();
40 }
41 while (!isStopped()) {
42 try {
43 ServerBootstrap b = new ServerBootstrap();
44 b.group(bossGroup, workerGroup)
45 .channel(NioServerSocketChannel.class)
46 .childHandler(new ChannelInitializer<SocketChannel>() {
47 @Override
48 public void initChannel(SocketChannel ch)
49 throws Exception {
50
51 ch.pipeline().addLast(new NettyServerHandler(serverUrl));
52 }
53 }).option(ChannelOption.SO_BACKLOG, 128)
54 .childOption(ChannelOption.SO_KEEPALIVE, true);
55 f = b.bind(serverPort).sync();
56 LOG.info("Server started and is ready for client connections....");
57 this.message = "Socket server started Successfully";
58 f.channel().closeFuture().sync();
59 } catch (Exception e) {
60 e.printStackTrace();
61 this.message = "Error starting server" + e;
62 }
63 }
64 }
65
66
67 public synchronized boolean isStopped() {
68 return this.isStopped;
69 }
70
71 public synchronized void stop() {
72 this.isStopped = true;
73 try {
74 workerGroup.shutdownGracefully();
75 bossGroup.shutdownGracefully();
76 } catch (Exception e) {
77 this.message = "Error closing server" + e;
78 throw new RuntimeException("Error closing server", e);
79 }
80 }
81
82 public String getMessage() {
83 return message;
84 }
85
86 public void setMessage(String message) {
87 this.message = message;
88 }
89 }
90