问题
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
from py4j.java_gateway import JavaGateway, GatewayParameters
gateway = JavaGateway(gateway_parameters=GatewayParameters(port=25335))
random = gateway.jvm.java.util.Random()
which resulted in the following error
py4j.protocol.Py4JNetworkError: An error occurred while trying to connect to the Java server (127.0.0.1:25335)
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
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
The above block yielded nothing. None of the ports could connect. I can't figure out where I am going wrong.
How do I find the port number which the java side is using?
I am using py4j version 0.10.7 and python 3.6.0
EDIT
I have used the same java code as used in the py4j tutorial
I have a file called java_stack.java
and py4j_gs.java
. Both are in the same directory. I'm calling `java py4j_gs.java from the terminal. These are the contents of the two files
java_stack.java
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");
}
}
py4j_gs.java
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");
}
}
回答1:
I also faced something same like
py4j.java_gateway:An error occurred while trying to connect to the Java server
while working on pyspark shell. To solve this first we need to start the java geteway server. After executing following java code my problem got resolve.
import py4j.GatewayServer;
public class Test {
public static void main(String[] args) {
Test app = new Test ();
// app is now the gateway.entry_point
GatewayServer server = new GatewayServer(app);
server.start();
}
}
来源:https://stackoverflow.com/questions/53759351/py4j-cannot-connect-to-java-server