View Javadoc

1   /*
2    * $Id: TcpServerSocketFactory.java 7963 2007-08-21 08:53:15Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.providers.tcp;
12  
13  import org.mule.util.StringUtils;
14  
15  import java.io.IOException;
16  import java.net.InetAddress;
17  import java.net.InetSocketAddress;
18  import java.net.ServerSocket;
19  import java.net.URI;
20  
21  public class TcpServerSocketFactory implements SimpleServerSocketFactory
22  {
23  
24      public ServerSocket createServerSocket(URI uri, int backlog, Boolean reuse) throws IOException
25      {
26          String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
27          InetAddress inetAddress = InetAddress.getByName(host);
28  
29          if (inetAddress.equals(InetAddress.getLocalHost())
30                  || inetAddress.isLoopbackAddress()
31                  || host.trim().equals("localhost"))
32          {
33              return createServerSocket(uri.getPort(), backlog, reuse);
34          }
35          else
36          {
37              return createServerSocket(inetAddress, uri.getPort(), backlog, reuse);
38          }
39      }
40  
41      public ServerSocket createServerSocket(InetAddress address, int port, int backlog, Boolean reuse) throws IOException
42      {
43          return configure(new ServerSocket(), reuse, new InetSocketAddress(address, port), backlog);
44      }
45  
46      public ServerSocket createServerSocket(int port, int backlog, Boolean reuse) throws IOException
47      {
48          return configure(new ServerSocket(), reuse, new InetSocketAddress(port), backlog);
49      }
50  
51      protected ServerSocket configure(ServerSocket socket, Boolean reuse, InetSocketAddress address, int backlog)
52              throws IOException
53      {
54          if (null != reuse && reuse.booleanValue() != socket.getReuseAddress())
55          {
56              socket.setReuseAddress(reuse.booleanValue());
57          }
58          // bind *after* setting so_reuseaddress
59          socket.bind(address, backlog);
60          return socket;
61      }
62  
63  }