00001 /* 00002 * Copyright (C) 2011 Google Inc. 00003 * 00004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 00005 * use this file except in compliance with the License. You may obtain a copy of 00006 * the License at 00007 * 00008 * http://www.apache.org/licenses/LICENSE-2.0 00009 * 00010 * Unless required by applicable law or agreed to in writing, software 00011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 00012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 00013 * License for the specific language governing permissions and limitations under 00014 * the License. 00015 */ 00016 00017 package org.ros.internal.transport.tcp; 00018 00019 import com.google.common.collect.Lists; 00020 00021 import org.jboss.netty.channel.Channel; 00022 import org.jboss.netty.channel.group.ChannelGroup; 00023 import org.jboss.netty.channel.group.DefaultChannelGroup; 00024 00025 import java.net.SocketAddress; 00026 import java.util.Collection; 00027 import java.util.List; 00028 import java.util.concurrent.Executor; 00029 00033 public class TcpClientManager { 00034 00035 private final ChannelGroup channelGroup; 00036 private final Collection<TcpClient> tcpClients; 00037 private final List<NamedChannelHandler> namedChannelHandlers; 00038 private final Executor executor; 00039 00040 public TcpClientManager(Executor executor) { 00041 this.executor = executor; 00042 channelGroup = new DefaultChannelGroup(); 00043 tcpClients = Lists.newArrayList(); 00044 namedChannelHandlers = Lists.newArrayList(); 00045 } 00046 00047 public void addNamedChannelHandler(NamedChannelHandler namedChannelHandler) { 00048 namedChannelHandlers.add(namedChannelHandler); 00049 } 00050 00051 public void addAllNamedChannelHandlers(List<NamedChannelHandler> namedChannelHandlers) { 00052 this.namedChannelHandlers.addAll(namedChannelHandlers); 00053 } 00054 00066 public TcpClient connect(String connectionName, SocketAddress socketAddress) { 00067 TcpClient tcpClient = new TcpClient(channelGroup, executor); 00068 tcpClient.addAllNamedChannelHandlers(namedChannelHandlers); 00069 tcpClient.connect(connectionName, socketAddress); 00070 tcpClients.add(tcpClient); 00071 return tcpClient; 00072 } 00073 00078 public void shutdown() { 00079 channelGroup.close().awaitUninterruptibly(); 00080 tcpClients.clear(); 00081 // We don't call channelFactory.releaseExternalResources() or 00082 // bootstrap.releaseExternalResources() since the only external resource is 00083 // the ExecutorService which must remain in the control of the overall 00084 // application. 00085 } 00086 }