Java tutorial
/* * Copyright 2014 Napolov Dmitry * * 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 org.aotorrent.tracker; import com.google.common.cache.Cache; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author dmitry 21.08.14 0:36 */ public class TorrentTracker implements Runnable { private final Logger LOGGER = LoggerFactory.getLogger(TorrentTracker.class); private final InetSocketAddress localSocketAddress; private Thread thread; private Map<String, Cache<InetSocketAddress, Integer>> torrents = new ConcurrentHashMap<>(); public TorrentTracker(InetSocketAddress localSocketAddress) { this.localSocketAddress = localSocketAddress; } @Override public void run() { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new TrackerChannelInitializer(torrents)); // Start the server. ChannelFuture f = b.bind(localSocketAddress.getPort()).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } catch (InterruptedException e) { LOGGER.error("Interrupted", e); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public Thread start() { thread = new Thread(this); thread.start(); return thread; } @Override public String toString() { return "TorrentTracker{" + "torrents=" + torrents + '}'; } }