I realize this question has been asked many times and answered many times (often from EJP, who clearly knows his stuff!), but I am still struggling.
I have "stolen" a simple RMI Adding Server and Client.
(Thank you,
http://www.scs.ryerson.ca/mes/courses/cps530/programs/rmi/Schildt/addTwoNumbers.html who then gives credit to Chapter 24 of "Java 2: The Complete Reference" by P.Naughton and H.Schildt.)
No matter what I try I still get this "Connection timed out" Exception.
Can anyone see what I've done wrong?
I suspect that there's something going on with the firewall, but if so, I don't know what to tell my IT guys to fix and change.
Thanks in advance!
Interface:
public interface AddServerIntf extends Remote {
double add(double d1, double d2) throws RemoteException;
}
Server:
public class SimpleRMIExServer {
public static void main(String[] args) throws Exception {
System.out.println("Class name " + SimpleRMIExServer.class.getSimpleName());
System.out.println("Path " + System.getProperty("user.dir"));
System.setProperty("java.rmi.server.codebase",
"file:///D:\\SimpleRMIExample\\lib\\SimpleRMIExample.jar");
Registry registry;
try {
registry = LocateRegistry.createRegistry(1099);
} catch (RemoteException remoteException) {
registry = LocateRegistry.getRegistry(1099);
}
AddServerImpl addServerImpl = new AddServerImpl();
registry.bind("AddServer", addServerImpl);
System.out.println("Located Registry " + registry.toString());
for (String boundName : registry.list()) {
System.out.println("Name bound: " + boundName);
}
Naming.rebind("SERVERNAME", addServerImpl);
System.out.println("Registry: " + registry);
System.out.println("");
System.out.println("Remote: " + addServerImpl);
}
}
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {
public AddServerImpl() throws RemoteException {
}
#Override
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
}
Client:
public class SimpleRMIExClient {
public static void main(String[] args) throws Exception {
final Registry registry = LocateRegistry.getRegistry("SERVERNAME", 1099);
AddServerIntf addServerIntf = (AddServerIntf) registry.lookup("AddServer");
System.out.println("The first number is: " + 10);
double d1 = Double.valueOf(10).doubleValue();
System.out.println("The second number is: " + 15);
double d2 = Double.valueOf(15).doubleValue();
System.out.println("The sum is: " + addServerIntf.add(d1, d2)); //Exception occurs here.
}
}
Output From Server:
D:\>java -jar SimpleRMIExServer.jar
Class name SimpleRMIExServer
Path D:\
Located Registry RegistryImpl[UnicastServerRef [liveRef: [endpoint:[XX.XX.XX.XX:
1099](local),objID:[0:0:0, 0]]]]
Name bound: AddServer
Registry: RegistryImpl[UnicastServerRef [liveRef: [endpoint:[XX.XX.XX.XX:1099](l
ocal),objID:[0:0:0, 0]]]]
Remote: AddServerImpl[UnicastServerRef [liveRef: [endpoint:[XX.XX.XX.XX:54119](l
ocal),objID:[2a7202aa:14492e5ea89:-7fff, -5034491972061237368]]]]
Output From Client:
debug:
The first number is: 10
The second number is: 15
Exception in thread "main" java.rmi.ConnectException: Connection refused to host: XX.XX.XX.XX; nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy0.add(Unknown Source)
at com.sun.proxy.$Proxy0.add(Unknown Source)
at simplermiexclient.SimpleRMIExClient.main(SimpleRMIExClient.java:35)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 minute 33 seconds)
Additionally, I used the command netstat -a and it showed:
LocalAddress ForeignAddress State
0.0.0.0:1099 SERVERNAME:0 LISTENING
[::]:1099 SERVERNAME:0 LISTENING
XX.XX.XX.XX:53373 SERVERNAME:1099 ESTABLISHED
(Among many other lines)
I have also seen:
LocalAddress ForeignAddress State
XX.XX.XX.XX:54138 SERVERNAME:1099 TIME_WAIT
Edit:
I tried adding in:
System.setProperty("java.rmi.server.hostname", "SERVERNAME");
to the server right after setting the codebase System property, based on EJP's recommendation to so many others to read Java RMI FAQ A.1.
When I did, this was the stack trace:
debug:
The first number is: 10
The second number is: 15
Exception in thread "main" java.rmi.ConnectException: Connection refused to host: SERVERNAME; nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy0.add(Unknown Source)
at com.sun.proxy.$Proxy0.add(Unknown Source)
at simplermiexclient.SimpleRMIExClient.main(SimpleRMIExClient.java:35)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 minute 15 seconds)
Answering my own question:
I have figured out the answer to my problem. I love to see others do that, it's good to be able to say it myself.
My final solution was a firewall problem, but I'd like to provide suggestions to anyone out there for HOW I solved my problem.
Break it down. Take my code above that really isn't my code and make a much simpler version of the RMI server and test it.
Start small and work your way up. Start with localhost make sure that works, then test on a separate PC (I had a virtual PC), then test on your server.
GET HELP! I searched the Internet A LOT. Thank you, EJP! Also, once I finally got it working on the Virtual PC, but not on the server, then I go my IT guys involved and they found a difference between the two. "There was a firewall setting on the PC that was related to Java that was not set on the server." - IT Guy (See: http://windows.microsoft.com/en-us/windows/communicate-through-windows-firewall#1TC=windows-7)
I realize what I've said here is nothing new and I know I've heard it many times, but sometimes it takes hearing it a thousand times to finally accept. Although it hasn't worked with my kids yet. ;-)
Good Luck.
(Answered by a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Answering my own question: I have figured out the answer to my problem. I love to see others do that, it's good to be able to say it myself.
My final solution was a firewall problem, but I'd like to provide suggestions to anyone out there for HOW I solved my problem.
Break it down. Take my code above that really isn't my code and make
a much simpler version of the RMI server and test it.
Start small and work your way up. Start with localhost make sure
that works, then test on a separate PC (I had a virtual PC), then
test on your server.
GET HELP! I searched the Internet A LOT. Thank you, EJP! Also, once
I finally got it working on the Virtual PC, but not on the server,
then I go my IT guys involved and they found a difference between
the two. "There was a firewall setting on the PC that was related to
Java that was not set on the server." - IT Guy (See:
http://windows.microsoft.com/en-us/windows/communicate-through-windows-firewall#1TC=windows-7
)
I realize what I've said here is nothing new and I know I've heard it many times, but sometimes it takes hearing it a thousand times to finally accept. Although it hasn't worked with my kids yet. ;-)
Good Luck.
Related
I saw a lot of "java.net.ConnectException: Connection refused" questions but none referring to timeout of this error. My problem is I have to connect to a server that, in some cases, is blocked (connected by another software to the same port). So, I'm doing a loop with some max retries to try to connect:
My current code (of course, is depending on a lot of configurations for my software, but is working fine):
public TCPConnector(TCPDefinition tcpDefinition) throws IAException {
ivTcpDefinition = tcpDefinition;
// Initialize the socket
boolean retry = false;
int counter = 1;
do {
try {
ivSocket = new Socket();
ivSocket.connect(new InetSocketAddress(tcpDefinition.getHostname(), tcpDefinition.getPort()), tcpDefinition.getConnectTimeOut());
ivSocket.setSoTimeout(tcpDefinition.getAckTimeOut());
retry = false;
}
catch (UnknownHostException uhe) {
throw new IAException(null, new StringBuffer("Can't find host: ").append(tcpDefinition.getHostname()).toString(), uhe);
}
catch (SocketException see) {
StringBuilder sb = new StringBuilder("Connection refused to host ").append(tcpDefinition.getHostname()).
append(" port ").append(tcpDefinition.getPort()).append(". Connection Attempt Nr. ").append(counter);
logger.error(sb.toString(), see);
retry = true;
if (counter++ > tcpDefinition.getConnectRetries())
throw new IAException(null, sb.toString(), see);
else
logger.error("will retry to connect");
}
catch (IOException ioe) {
StringBuilder sb = new StringBuilder("I/O error while connecting to host ").append(tcpDefinition.getHostname()).
append(" port ").append(tcpDefinition.getPort()).append(". Connection Attempt Nr. ").append(counter);
logger.error(sb.toString(), ioe);
retry = true;
if (counter++ > tcpDefinition.getConnectRetries())
throw new IAException(null, sb.toString(), ioe);
else
logger.error("will retry to connect");
}
}
while (retry);
}
Well, the problem is this:
On Windows, every second, the SocketException is thrown, instead the IOException, while I have configured a timeout of 5000 msec to ivSocket.connect
On Linux, this is thrown every millisecond!!
Windows:
2019-12-05 12:40:47,609 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 1
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
2019-12-05 12:40:48,703 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 2
java.net.ConnectException: Connection refused: connect
Linux:
2019-12-05 12:45:47,609 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 1
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
2019-12-05 12:45:47,610 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - Connection refused to host localhost port 13002. Connection Attempt Nr. 2
java.net.ConnectException: Connection refused: connect
Why the timeout is not executed? Well this is not exactly right. If I configure a timeout less than 1 second on Windows, then the timeout is executed. 500 msec:
2019-12-05 11:47:07,375 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - I/O error while connecting to host localhost port 13002. Connection Attempt Nr. 1
java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
2019-12-05 11:47:07,875 ERROR DefaultQuartzScheduler_Worker-1 TCPConnector - I/O error while connecting to host localhost port 13002. Connection Attempt Nr. 2
java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
It is possible to configure a "connect refuse" timeout?
There is no such thing as a "connection refused timeout".
"Connection refused" happens when the server sees the connection request, but there is no service listening for connections on the IP + port that the request is directed to. The server then "refuses" the connection. This typically happens instantly, so so no timeout is triggered.
"Connection timed out" happens (typically) when something stops the connection request from reaching the server1, 2. So the client-side will wait for the response from the server, and then resend / wait a few times. And eventually the time allotted for establishing a connection will expire ... and the connection times out.
As you can see these are different scenarios. And they are reported back to the Java client-side differently.
So the reason you are not getting timeouts is that the "connection refused" responses are coming back quick enough that your configured timeout is not exceeded.
That might also explain why setting the connect timeout small might have changed the behavior. There may also be issues with the granularity of the timeout that the OS allows Java to set.
To investigate this further, I think we would need a minimal reproducible example. For example, we need to see how you have implemented the code that manages the server-socket and accepts connections on the server side.
1 - The blockage could be on the server's reply packets.
2 - There are various possible causes for this kind of thing. The most likely are a firewall blocking traffic somewhere, a network routing problem, or using a private IP address on the wrong network.
Kind Attn Moderators: Before marking this query as duplicate, please note I have checked these questions...
java.net.SocketException: Connection reset
What's causing my java.net.SocketException: Connection reset?
Getting error "java.net.SocketException: Connection reset"
...and was unable to fix the issue. Also I believe the context & error is different from those, thus seeking help here.
Context: Download a csv file from NSEIndia website to a local folder (Note: Am able to download CSV files from other random websites).
Issue: Returns an error - javax.net.ssl.SSLException: Connection reset (Full error pasted below)
Observation: I am perplexed, as I faced this same issue yesterday, but after a couple of retries, it worked. I made no changes to code or settings.
Question: Is there anything I can do from my end to ensure this error is not seen with this specific website ?
Code:
// Using FileUtils from -> import org.apache.commons.io.FileUtils;
try {
FileUtils.copyURLToFile(new URL("https://www.nseindia.com/content/fo/fo_mktlots.csv"),new File("D:\\Download\\t1.csv"));
} catch (IOException e) {
e.printStackTrace();
}
Error:
javax.net.ssl.SSLException: Connection reset
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:127)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:324)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:267)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:262)
at java.base/sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1652)
at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:1038)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:245)
at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:285)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:344)
at java.base/sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:746)
at java.base/sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:689)
at java.base/sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:717)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1610)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)
at java.base/java.net.URL.openStream(URL.java:1162)
at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1456)
at main.Test.dummy3(Test.java:327)
at main.Test.main(Test.java:59)
Suppressed: java.net.SocketException: Connection reset by peer
at java.base/sun.nio.ch.NioSocketImpl.implWrite(NioSocketImpl.java:421)
at java.base/sun.nio.ch.NioSocketImpl.write(NioSocketImpl.java:441)
at java.base/sun.nio.ch.NioSocketImpl$2.write(NioSocketImpl.java:825)
at java.base/java.net.Socket$SocketOutputStream.write(Socket.java:1007)
at java.base/sun.security.ssl.SSLSocketOutputRecord.encodeAlert(SSLSocketOutputRecord.java:82)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:355)
... 17 more
Caused by: java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:324)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:351)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:802)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:937)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:450)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:68)
at java.base/sun.security.ssl.SSLSocketImpl.readApplicationRecord(SSLSocketImpl.java:1409)
at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:1022)
... 13 more
I do not have a lot of experience in Java and would appreciate if you bring a light on the question.
I have the following piece of code (method) to establish the JDBC connection with a PostgreSQL database :
public void establishDBConnection() throws SQLException {
try (Connection connection = DriverManager.getConnection(
"jdbc:postgresql://" + dbServer + ":" + dbPort + "/" +
dbDatabase, dbUser, dbPassword))
catch (SQLException e) {
logger.error("Connection to Postgres Database Failed: " +
e.printStackTrace();
}
}
I expect that the SQLException would be caught by the catch block as soon as the method can't establish connection with the database (server is down). The catch block puts the exception on the console but I see that the same exception is displayed earlier right after the getConnection method execution. Thus, I have 2 quite the same exceptions on the console. See below.
The question is what is the reason for this and how to force the application to display only the exception generated by the catch block.
Logs:
Jul 07, 2017 9:11:53 PM org.postgresql.Driver connect
SEVERE: Connection error:
**org.postgresql.util.PSQLException: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:265)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
at org.postgresql.Driver.makeConnection(Driver.java:431)
at org.postgresql.Driver.connect(Driver.java:247)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at excel2db.service.impl.DBConnectionPostgresImpl.establishDBConnection(DBConnectionPostgresImpl.java:38)
at excel2db.excel2db.main(excel2db.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.postgresql.core.PGStream.<init>(PGStream.java:62)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
... 13 more
21:11:53.465 [main] ERROR e.s.impl.DBConnectionPostgresImpl - **Connection to Postgres Database Failed: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
There is only one exception being printed in your example: the SQLException being caught. What you think is a second exception is only (as the text shows) the cause of the SQLException: Postgres throws a SQLException, which is itself being thrown because there was a network ConnectException when Portgres tried to connect.
This chain of exceptions is very handy when you need to diagnose a failure. It allows going back to the original, low-level source of a problem. Just like, for example, it can be useful to know that you didn't got your mail (NoMailException) because the post office is on strike (OnStrikeException), because the government decided to lower the wages (WagesTooLowException). If you just had the original NoMailException, you wouldn't be able to know the reason why you got no mail, know that it's probably temporary, etc.
In this particular case, you can deduce that it was impossible to connect to the server, and not for example, that the password was incorrect.
Chaining exceptions is simply achieved by calling one of the exception constructors that take another exception as argument (most exceptions do). See https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html#Exception-java.lang.String-java.lang.Throwable-.
You need to load the driver's class into memory. Try This code :
try {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(jdbc:postgresql://server_address:5432/database_name?user=usernam&password=password);
} catch (Exception exception) {
exception.printStackTrace();
}
I have orace 11g running on 192.168.1.217 and I am trying to connect it using JDBC driver with java and it gives me following error
IO Error: The Network Adapter could not establish the connection
Library I am using is ojdbc6.jar
Here is my code
public void makeOracleConnection() {
try {
Class.forName("oracle.jdbc.OracleDriver");
oraCon = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.217:1521:orcl", "hr", "hr");
oraStmt = oraCon.createStatement();
oraRsStmt=oraCon.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
} catch (Exception e) {
System.out.println("Error while making connection with Database : " + e.getMessage());
}
}
I have also tried to ping on 192.168.1.217 then pins is successful.
Also TNSLISTENER is running on that machine.
please help.
Please find print stack trace here
run:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:657)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:560)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at test.oracle.makeOracleConnection(oracle.java:30)
at test.oracle.<init>(oracle.java:21)
at test.oracle.main(oracle.java:69)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:230)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
... 8 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:163)
at oracle.net.nt.ConnOption.connect(ConnOption.java:159)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428)
... 13 more
BUILD SUCCESSFUL (total time: 1 second)
You get the error
java.net.ConnectException: Connection refused: connect
Which means that there is nothing listening on the machine and port you are trying to connect to. Your Java code looks correct so I would continue to investigate that Oracle is actually listening on port 1521 on 192.168.1.217.
If you run run netstat -n on the server you should find a line that looks like
TCP [::]:1521 [::]:0 LISTENING
If something really is listening on that port. If you do not find that line, check your Oracle configuration.
Try to connect with some other tool, ie sqlplus to verify that the issue is not with Oracle. If you cannot connect with sqlplus/sql developer, make sure that your oracle is configured to allow remote connections, and also listens on given addresses/ports
public void makeOracleConnection() {
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection oraCon = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.217:1521:orcl", "hr", "hr");
Statement oraStmt = oraCon.createStatement();
//oraRsStmt=oraCon.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE);
ResultSet rs = oraStmt.executeQuery("select hello as result from dual");
while(rs.next()) {
System.out.println(rs.getString("result"));
}
}
catch (Exception e)
System.out.println("Error while making connection with Database : " + e.getMessage());
}
}
Try this out. Hope it'll help. I also don't like your connection path. Is it right? I think it should be something like this:
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=YES)(ADDRESS=(PROTOCOL=tcp)(HOST=ip adres)(PORT=port)))(CONNECT_DATA=(SERVICE_NAME = orcl)))","username","password"
I've tried to used RMI, here is server side. at first it worked without any exception, but now after three times whenever i try to run the below code, i will get some errors
The code is:
import java.rmi.server.UnicastRemoteObject;
/**
* Created by elyas on 12/11/14 AD.
*/
public class LogicImplement extends UnicastRemoteObject implements Logic
{
public LogicImplement() throws Exception
{
java.rmi.registry.LocateRegistry.createRegistry(6060);
java.rmi.Naming.rebind("Object1",this);
}
#Override
public int sum(int a, int b) throws Exception
{
int result = a + b;
System.out.println("ana sum executed");
return result;
}
public static void main(String[] args)
{
try
{
LogicImplement logicImplement = new LogicImplement();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
The error is like this: i've tried to change the Object1 to for example Object2, but again i will get error, also i change the port number...
what is solution?
java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:341)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at java.rmi.Naming.rebind(Naming.java:177)
at LogicImplement.<init>(LogicImplement.java:12)
at LogicImplement.main(LogicImplement.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 12 more
java.net.ConnectException: Connection refused
There could be couple of reasons for this exception:
You have not started your rmiregistry in background.
You are trying to connect to the wrong port number.
Your firewall maybe blocking the connections.
The Answer was very simple, By default, the registry runs on port 1099. To start the registry on a different port, specify the port number on the command line. Do not forget to unset your CLASSPATH environment variable. for more information check this link: Running the Example Programs
** So for fixing this code i must change the port number form 6060 to 1099
notice that: if 1099 is used by other services you have to test 1100, and if 1100 is used too, you have yo use 1101 and so on. :-)
Since this was a port number issue, there is another way to start the registry on the port number you want:
java.rmi.registry.Registry rmiRegistry = java.rmi.registry.LocateRegistry.
createRegistry(6060); // Creates a registry on 6060
rmiRegistry.rebind("Object1",this); // Binds to registry created on 6060
You haven't started the RMI Registry.
When you get past this, if it still happens when calling the remote method, see item A.1 of the RMI FAQ.