com.github.dreamhead.moco.internal.MocoServer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of moco-core Show documentation
Show all versions of moco-core Show documentation
Moco is an easy setup stub framework, mainly focusing on testing and integration.
package com.github.dreamhead.moco.internal;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;
public class MocoServer {
private EventLoopGroup group;
private ChannelFuture future;
public MocoServer() {
group = new NioEventLoopGroup();
}
public int start(final int port, final ChannelInitializer extends Channel> pipelineFactory) {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(pipelineFactory);
try {
future = bootstrap.bind(port).sync();
SocketAddress socketAddress = future.channel().localAddress();
return ((InetSocketAddress) socketAddress).getPort();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void stop() {
doStop();
}
private void doStop() {
if (future != null) {
future.channel().close().syncUninterruptibly();
future = null;
}
if (group != null) {
Future> groupFuture = group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
try {
groupFuture.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
group = null;
}
}
}