I've seen few threads about this topic but I still can't figure out what's wrong. Following is the code:
import java.sql.*;
public class SQL
{
public static void main(String[] args)
{
Connection conn = null;
String url = "jdbc:mysql://mysql1.oyo.co.il:3306/";
String dbName = "sdarot2_winner";
String driver = "com.mysql.jdbc.Driver";
String userName = "";
String password = "";
String table = "LEADER_CAM_PRODUCTS";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}catch (Exception e) {
System.out.println(e);
}
}
}
And here is the error I get:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying > > exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection timed out: connect
STACKTRACE:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.(Unknown Source)
at java.net.Socket.(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2744)
at com.mysql.jdbc.Connection.(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at SQL.main(SQL.java:17)
** END NESTED EXCEPTION **
Last packet sent to the server was 1 ms ago.
Here is few things I found around:
The I.P/domain or port is incorrect
The I.P/domain or port (i.e service) is down
The I.P/domain is taking longer than your default timeout to respond
You have a firewall that is blocking requests or responses on whatever port you are using
You have a firewall that is blocking requests to that particular host
Your internet access is down
a) it is correct.
b) it's not down since I got a website that is working right now with that database.
c) how can I check that?I don't think that it's the problem since as I said I got a running website on this database.
d) now way because the same reason I mentioned above.
e) samem as d
So what I'm doing wrong?how come a php code can work with sql but java gives me errors?
Thank you.
As an experiment, try connecting to port 3306 on mysql1.oyo.co.il using your system's telnet command. Or some other utility (for example nc or netcat) that opens a raw TCP/IP connection. Depending on your OS / distro, you may have to locate and install a suitable command to help you with this trouble-shooting. Observe what happens.
Re your diagnosis:
a) it is correct.
If you say so ...
b) it's not down since I got a website that is working right now with that database.
At best you have demonstrated that the host is working. The web service on port 80 and the MySQL service on port 3306 are different services. (And in fact, it is possible that mysql1.oyo.co.il is doing clever packet routing tricks so that traffic on different ports is being tranparently routed to different hosts or virtual hosts.)
c) how can I check that?
Try changing / increasing the timeout.
I don't think that it's the problem since as I said I got a running website on this database.
My guess it is not a timeout issue ... but as I said above, the fact you got a website says NOTHING about whether the MySQL service is running.
d) now way because the same reason I mentioned above.
You've only demonstrated that you can get to port 80 ... see above
e) samem as d
You've only demonstrated that you can get to port 80 ... see above
Based on the above, it is plausible that:
you have a local firewall problem,
the MySQL service on that port is not currently running,
networking routing on the service side are broken for traffic on that port,
the MySQL service has been permanently turned off, or
the service's firewall has been configured to not accept network connections from random (or specific) places, including yours.
The fact that you are seeing a timeout rather than a "connection refused" suggests that this is more likely to be a networking or firewalling issue than a problem with the MySQL service endpoint itself.
My guess is that "they" have withdrawn the service ... and that you are not supposed to use it anymore. (Providing a public MySQL database service strikes me as an odd thing to do ... as well as being problematic from a security and administration standpoint.)
'Connection timed out' indicates either:
a server-side firewall that is deliberately ignoring your connection request
a network topology problem such that IP packets aren't getting through
the server host itself is down.
Most likely it is the first.
Note that, contrary to other answers here, it doesn't indicate that the server program is down, or a local firewall problem at the client. The former would cause 'connection refused' and the latter would give you something along the lines of 'permission denied', depending on your platform.
Related
I have a question about MySQL/JDBC connections in Java.
I wrote an application that successfully communicates with a database, but the issue that I recently found out was that my DB connection was dropping, and I need the application to have a connection to the DB at all times.
This is a small snipplet of the error I was getting:
com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 89,225,584 milliseconds ago. The last packet sent successfully to the server was 89,225,584 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
This is also a snipplet of the constructor for my DBConnections class:
private final String url = "jdbc:mysql://localhost:3306/", database.....;
private Connection connection;
public DBConnector(){
try {
// Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url+database, username, password);
} catch (Exception ex) {
System.out.println("Error: " + ex);
}
}
In the errors section, I noticed it's telling me to add autoReconnect=true, I wondered; will my connection still stay up for longer if I structured the connection class like this:
connection = DriverManager.getConnection(url+database+"?autoReconnect=true", username, password);
If not, what else could I do to make sure my connection doesn't drop?
What I would suggest is to use a connection pool (Apache DBCP or HikariCP - the last one is currently having the best performance out of all solutions on the market) with configuration of testing connection before borrowing it from the pool. Depending on the library there should be an option like setTestOnBorrow(true).
In real applications you should always use connection pool instead of manually handling connections.
I'm working on an Android app (Java 8, apache.commons.net.ftp 3.6, Min: API 24/target: API 27) that connects to an FTP server but I'm experiencing a weird problem:
If I connect to one of the public test servers (e.g. speedtest.tele2.net) or the IP address directly (e.g. 10.1.1.123), it works fine.
If I add a typo in a "normal" address on purpose (e.g. sspeedtest.tele2.net), I get the expected java.net.UnknownHostException but if I add a typo to an IP address, no matter if it's in the same network or not (e.g. 10.1.1.223), nothing else happens - no exception, no error, no result, even after the set timeout time has passed.
Code:
FTPClient f = new FTPClient();
f.setDefaultTimeout(5000); //5 seconds
try {
f.connect(url,port);
boolean b = f.login(username,password);
Log.d(TAG,"logged in="+b+", connected="+f.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
I let it run a little bit longer and finally, after 1 minute and 16 seconds an exception was thrown:
W/System.err: java.net.ConnectException: Connection refused
I've tried this multiple times and the exception always seems to be thrown after 1:16.
How do I make this respect the default timeout too? Is there a different one I have to use?
You're setting a timeout for receiving data. The timeout for opening a connection is separate, and set with the setConnectTimeout(int connectTimeout) method:
FTPClient f = new FTPClient();
f.setConnectTimeout(5000); // 5 second timeout to open connection
f.setDefaultTimeout(5000); // 5 second timeout when receiving data
If you get "connection refused" that means the IP address is actually used by some host in the network. If there was nothing at that address, you would get an error more along the lines of "no route to host".
We are getting the following exception.
com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 43249415092 not found on server xx.xx.xx.xx:27017'
at com.mongodb.connection.GetMoreProtocol.receiveMessage(GetMoreProtocol.java:115)
at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:68)
at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:37)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:155)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:219)
at com.mongodb.connection.DefaultServerConnection.getMore(DefaultServerConnection.java:194)
at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:197)
at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:93)
at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
at com.mongodb.DBCursor.hasNext(DBCursor.java:152)
We are unable to find the root cause since we are getting this exception rarely.
We also observed that the application is unable to read from cursor
but no exception is thrown.
In cases where no exception is thrown,we took the thread dump and found that the thread reading from mongo is in RUNNABLE state.
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at com.mongodb.connection.SocketStream.read(SocketStream.java:85)
at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:503)
at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:221)
at com.mongodb.connection.UsageTrackingInternalConnection.receiveMessage(UsageTrackingInternalConnection.java:102)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.receiveMessage(DefaultConnectionPool.java:416)
at com.mongodb.connection.GetMoreProtocol.receiveMessage(GetMoreProtocol.java:112)
at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:68)
at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:37)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:155)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:219)
at com.mongodb.connection.DefaultServerConnection.getMore(DefaultServerConnection.java:194)
at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:197)
at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:93)
at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
at com.mongodb.DBCursor.hasNext(DBCursor.java:152)
please help me in finding the root cause of this issue?
Recently, I met the same issue. After long time research, I figured out it. In my scenario, I have 4 mongos, which behind a load balance(return the mongos IP address randomly). In my connection string, I use the load balance host as the address of the mongoDB cluster .
When the app start, the mongoDB driver create a server with a connection pool. In the connection pool, there are mixed connections coming from 4 mongos.
When you query a large data(large than the batchSize), The first batch data comes from mongos A, then when the following batch request is pushed, the connection may connect to mongos B/C or D(source code). They can't find the cursor of course. So, the MongoCursorNotFoundException is thrown.
How to handle it?
Do not use balance host in your connection string. use all mongos IP address instead. Let mongoDB driver itself to balance the request.
WRONG: mongodb://your.load.balance.host:27000/yourDB?connectTimeoutMS=60000&minPoolSize=100&maxPoolSize=100&waitqueuemultiple=20&waitqueuetimeoutms=60000
RIGHT: mongodb://10.0.0.1:27017,10.0.0.2:27017,10.0.0.3:27017,10.0.0.4:27017/yourDB?connectTimeoutMS=60000&minPoolSize=100&maxPoolSize=100&waitqueuemultiple=20&waitqueuetimeoutms=60000
There is a better solution: You can configure a unique and dedicated host for each mongos, then modify the RIGHT connection string: replace the IP address by this host.
I am using AmazonSQSAsyncClient to connect with Amazon SQS, but sometimes I see the following execution in the logs:
INFO [AmazonHttpClient:444] Unable to execute HTTP request: Connection reset
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:755)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:166)
at org.apache.http.impl.io.SocketInputBuffer.fillBuffer(SocketInputBuffer.java:90)
at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:281)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:92)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at com.amazonaws.http.protocol.SdkHttpRequestExecutor.doReceiveResponse(SdkHttpRequestExecutor.java:66)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:712)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:517)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:380)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:229)
at com.amazonaws.services.sqs.AmazonSQSClient.invoke(AmazonSQSClient.java:2169)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:468)
at com.amazonaws.services.sqs.AmazonSQSClient.getQueueUrl(AmazonSQSClient.java:1476)
I am using the AmazonSQSAsyncClient through out the application as singleton.
Code snippet is below.
static{
if(sqsObj == null){
sqsObj = new AmazonSQSAsyncClient(new ClasspathPropertiesFileCredentialsProvider("app.properties"));
sqsObj.setRegion(Region.getRegion(Regions.valueOf("sample region"));
}
}
By using sqsobj, I am doing operations like create queue, send message and receive messages. It works fine but some time throws the exception as above. After restarting the application it works fine for sometime.
I am using aws-java-sdk-1.7.1.
Please suggest on this.
The "connection reset" means that the other party (i.e. the server) closed the connection.
Internally the SDK builds and reuses a http connection to not have to open a connection every time you make a request.
The log message tells you that the connection was reset, but normally this is not something to worry about. The SDK will retry automatically in cases like this. So if you are only seeing this sporadically in the logs but everything works as expected you should probably not worry about it
I've created a chat program which required the user to select either the client or server role. My approach at removing this requirement is to have every user start their own server where they'll get messages from. This should allow me to have two clients talk to the the other without having to put a server in between them.
Right now I've modified my program in such a way that the client side does the sending and the server does the receiving.
Note that communication between the two programs worked perfectly fine up untill these changes. However, now that I've changed some stuff an error occurs as early as when I create a socket.
The flow of my program untill the problem is as follows:
Program starts
Server starts automatically, binded to local port 6666
Connection config pops up, user clicks the save button (target host and port are saved)
User clicks the connect button
Program creates a client thread
Thread creates the socket and initiates the outbound stream
After some debugging I've found that this socket is never created.
When the flow enters this stage (last item in the list), only the 'First test' gets executed.
public void run() {
System.out.println("First test");
createConnection();
System.out.println("Second test");
initiateIO();
}
private void createConnection() {
try {
socket = new Socket(host, port);
} catch (UnknownHostException e) {
OutputUtil.showErrorMessage("Couldn't bind socket to unknown host", "Unknown host");
} catch (IOException e) {
OutputUtil.showErrorMessage("General IO error at creating client socket", "IO error");
}
}
private void initiateIO() {
try {
outbound = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
OutputUtil.showErrorMessage("Couldn't load IO streams from client", "IO Error");
}
}
Output:
Console: First test
Popup: General IO error at creating client socket
Console: Second test
Console: NPE at `outbound.close()`
I'm assuming the NPE is a result of the first error, considering a method from the socket is invoked when creating the PrintWriter. It should also be noted that it takes around 10 seconds to show the first error.
At first I thought the error might be introduced because both the local server and the connection with the other client use port 6666, but after creating a link on port 6667 the problem still occurred. Which makes sense upon review.
When my debugger points at the line where outbound is initialized (after the "second test" message, socket has value null.
My question is: why can't the socket be created? The documentation only specifies
IOException - if an I/O error occurs when creating the socket.
which isn't of much use.
Full source code can be found here for a better overview.
Edit: Printed the stacktrace from the first, main error.
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at core.Client.createConnection(Client.java:30)
at core.Client.run(Client.java:64)
at java.lang.Thread.run(Unknown Source)
This is a firewall problem. The target port you specified wasn't open in the target's firewall.
The server may also not have been running, but if that was the only problem it would have been 'connection refused', not 'connection timed out: connect'.