001 /*--------------------------------------------------------------------------+
002 $Id: SmartRMISocketFactory.java 28668 2010-06-23 14:46:45Z heineman $
003 | |
004 | Copyright 2005-2010 Technische Universitaet Muenchen |
005 | |
006 | Licensed under the Apache License, Version 2.0 (the "License"); |
007 | you may not use this file except in compliance with the License. |
008 | You may obtain a copy of the License at |
009 | |
010 | http://www.apache.org/licenses/LICENSE-2.0 |
011 | |
012 | Unless required by applicable law or agreed to in writing, software |
013 | distributed under the License is distributed on an "AS IS" BASIS, |
014 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
015 | See the License for the specific language governing permissions and |
016 | limitations under the License. |
017 +--------------------------------------------------------------------------*/
018 package edu.tum.cs.commons.net;
019
020 import java.io.IOException;
021 import java.net.ServerSocket;
022 import java.net.Socket;
023 import java.rmi.server.RMISocketFactory;
024
025 /**
026 * A {@link RMISocketFactory} that adjusts flags on the sockets used. One is
027 * that for the server socket the reuse flag is set, which allows fast
028 * reopening. Second, an optional timeout can be set.
029 *
030 * @author hummelb
031 * @author $Author: heineman $
032 * @version $Rev: 28668 $
033 * @levd.rating GREEN Hash: 676BF40E769C33456EE7029EE0E3949A
034 */
035 public class SmartRMISocketFactory extends RMISocketFactory {
036
037 /** Timeout in seconds. */
038 private final int timeoutSeconds;
039
040 /** Constructor. No timeout is set. */
041 public SmartRMISocketFactory() {
042 this(-1);
043 }
044
045 /** Constructor */
046 public SmartRMISocketFactory(int timeoutSeconds) {
047 this.timeoutSeconds = timeoutSeconds;
048 }
049
050 /** {@inheritDoc} */
051 @Override
052 public Socket createSocket(String host, int port) throws IOException {
053 Socket socket = getDefaultSocketFactory().createSocket(host, port);
054 if (timeoutSeconds > 0) {
055 socket.setSoTimeout(timeoutSeconds * 1000);
056 }
057 return socket;
058 }
059
060 /** {@inheritDoc} */
061 @Override
062 public ServerSocket createServerSocket(int port) throws IOException {
063 ServerSocket socket = getDefaultSocketFactory()
064 .createServerSocket(port);
065 socket.setReuseAddress(true);
066 return socket;
067 }
068 }