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