Java tutorial
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.openshift; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.DefaultThreadFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; abstract class AbstractTunnel { private final int localPort; // Netty worker group private final EventLoopGroup bossGroup; private final EventLoopGroup workerGroup; // Client connections private final Map<Channel, Channel> clients = new ConcurrentHashMap<Channel, Channel>(); // Shutdown local threads and close sockets private final AtomicBoolean shutdown = new AtomicBoolean(); private volatile Channel acceptorChannel; protected AbstractTunnel(int localPort) { this.localPort = localPort; this.bossGroup = new NioEventLoopGroup(5, new DefaultThreadFactory("server-channel-")); this.workerGroup = new NioEventLoopGroup(5, new DefaultThreadFactory("client-channel-")); } public void start() throws Exception { ServerBootstrap bootstrap = createBootstrap(localPort); // Create listener acceptorChannel = bootstrap.bind(localPort).sync().channel(); } public void stop() throws Exception { shutdown.set(true); try { // Wait for channel to be closed if (acceptorChannel != null) { acceptorChannel.close(); acceptorChannel.closeFuture().sync(); } } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } EventLoopGroup getBossGroup() { return bossGroup; } EventLoopGroup getWorkerGroup() { return workerGroup; } void registerChannel(Channel socket, Channel forward) { clients.put(socket, forward); } protected abstract ServerBootstrap createBootstrap(int localPort) throws Exception; }