title: Py4j Cannot connect to Java Server
body: <p>I was trying to write a simple program to setup a connection between python and java using py4j. I wrote the following two lines hoping that everything would run since I'm not making any changes</p>
  
  <pre><code>from py4j.java_gateway import JavaGateway, GatewayParameters
  gateway = JavaGateway(gateway_parameters=GatewayParameters(port=25335))
  random = gateway.jvm.java.util.Random()
  </code></pre>
  
  <p>which resulted in the following error</p>
  
  <blockquote>
    <p>py4j.protocol.Py4JNetworkError: An error occurred while trying to connect to the Java server (127.0.0.1:25335)</p>
  </blockquote>
  
  <p>I looked around for a while and read that this might happen if java is listening on to a different port. So I wrote a for block to see what happens</p>
  
  <pre><code>for i in range(65535+1):
      try:
          gateway = JavaGateway(gateway_parameters=GatewayParameters(port=i))
          random = gateway.jvm.java.util.Random()
          print("passed port num", str(i))
      except:
          pass
  </code></pre>
  
  <p>The above block yielded nothing. None of the ports could connect. I can't figure out where I am going wrong. </p>
  
  <p>How do I find the port number which the java side is using?</p>
  
  <p>I am using py4j version 0.10.7 and python 3.6.0</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have used the same java code as used in the <a href="https://www.py4j.org/getting_started.html" rel="nofollow noreferrer">py4j tutorial</a> </p>
  
  <p>I have a file called <code>java_stack.java</code> and <code>py4j_gs.java</code>. Both are in the same directory. I'm calling  `java py4j_gs.java from the terminal. These are the contents of the two files</p>
  
  <p><strong>java_stack.java</strong></p>
  
  <pre><code>package py4j.examples;    
  import py4j.GatewayServer;
  public class StackEntryPoint {
      private Stack stack;
      public StackEntryPoint() {
        stack = new Stack();
        stack.push("Initial Item");
      }
      public Stack getStack() {
          return stack;
      }
      public static void main(String[] args) {
          GatewayServer gatewayServer = new GatewayServer(new StackEntryPoint());
          gatewayServer.start();
          System.out.println("Gateway Server Started");
      }    
  }
  </code></pre>
  
  <p><strong>py4j_gs.java</strong></p>
  
  <pre><code>package py4j.examples;
  import py4j.GatewayServer;
  public class StackEntryPoint {
      private Stack stack;
      public StackEntryPoint() {
        stack = new Stack();
        stack.push("Initial Item");
      }
      public Stack getStack() {
          return stack;
      }
      public static void main(String[] args) {
          GatewayServer gatewayServer = new GatewayServer(new StackEntryPoint());
          gatewayServer.start();
          System.out.println("Gateway Server Started");
      }
  }
  </code></pre>