Socket can't be created, throws IOException - java

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'.

Related

Prevent an app from binding to a socket that is already bound

How to prevent a Java app from binding to a socket that another process is already bound to on Windows?
I have an issue where I have a Java application that is listening on port 80. The application starts fine and reports no exceptions. I couldn't figure out why I couldn't connect on port 80. Other ports worked fine. I checked netstat for other processes listening on 80 and found Skype. I didn't think that was possible, but after some research, I'm guessing Skype is listening with the SO_REUSEADDR option. In this state the accepting application is indeterminate. I would like my Java application to fail in this instance with a bind exception (or other).
It looks like I could use SO_EXCLUSIVEADDRUSE if I had access to that option via Java but I don't think that is possible. There are lots of questions and answers around SO_REUSEADDR but none that I could find that answered my question. This isn't just about Skype (I can turn off the listening part), I want my program to be more robust in this situation.
This is snippet from netstat -abn on a Windows 7 box:
Proto Local Address Foreign Address State
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING [java.exe]
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING [Skype.exe]
This is why I'm assuming that Skype is using SO_REUSEADDR
The processes don't appear to be listening on different interfaces.
Here is a snippet of the code. The port is 80:
myServerSocket = new ServerSocket(myTcpPort);
while (true) {
new HTTPSession( myServerSocket.accept(), threadPool );
}
As further information I created a sample program to minimize any side effects or mishandled messages.
import java.net.ServerSocket;
public class PortTest
{
public static void main(String[] args)
{
System.out.println( "Hit Ctrl-C to stop.\n" );
try {
ServerSocket myServerSocket = new ServerSocket(80);
System.out.println( "Before the accept() call.");
myServerSocket.accept();
System.out.println( "After the accept() call." );
}
catch (Exception ex ) {
System.out.println("Error listening.");
ex.printStackTrace();
}
}
}
I still don't get an exception when running this sample program (PortTest) and when Skype is running and listening on port 80. And to further test, I executed a second instance PortTest and I do see the port in use message.
Error listening.
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at PortTest.main(PortTest.java:10)
socket = new ServerSocket(0);
Will automatically select you a free port.
Furthermore, this code will tell you wether a port is avaliable:
boolean portAvaliable = true;
ServerSocket s = null;
try {
s = new ServerSocket(yourPort);
}
catch (IOException e) {
portAvaliable = false;
}
finally {
if (s != null)
try {
s.close();
}
catch (IOException e) {
//handle the exception
}
}
Check the boolean value from portAvaliable in order to identify the port status.
For anyone wondering, Java prior to 7u25 had this problem.
Here's an excerpt from the release note of Java 7u25:
Change in Networking API Implementation on Windows platforms
The
implementation of the networking APIs has been changed on Windows to
use the SO_EXCLUSIVEADDRUSE socket option by default. This change is
necessary to address anomalies that arise when using both IPv4 and
IPv6 applications that require to bind to the same port.
The problem is exclusive to Windows because of the funky way[1] SO_REUSEADDR[2] works there.
[1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx
[2] Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?

FTP client class is not connecting

FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("32.178.10.121");
client.login("XXX", "XXX");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried this but each time it gives time out of bound exception and by other means of i am successfully getting connected but nt from here what could be reason.
this is the 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.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:53)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:162)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:250)
at forTesting.FileUploadDemo.main(FileUploadDemo.java:15)
First try to set the proxy details like below
FTPClient ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
Then try to connect as you are doing and let me know if the error is gone.
If the error persists then check the firewall setting for the FTP server. Also try to connect from the System with some GUI tool like Filezilla to connect to the server.
You might want to try using PASV mode, if you're behind a firewall or proxy. Have a look here:
In situations where the client is behind a firewall and unable to
accept incoming TCP connections, passive mode may be used. In this
mode, the client uses the control connection to send a PASV command to
the server and then receives a server IP address and server port
number from the server, which the client then uses to open a
data connection from an arbitrary client port to the server IP address
and server port number received.

Java networking server-client error

I'm trying to program a (simple, for starters) server-client thingy, just to establish a connection and see if it works. And it does. As long as I stay inside my own four walls/network. As soon as I try to go via my routers IP the client produces a mighty fine error message. All the usual suspects have been eliminated: Router Port forwarding is on, the firewall doesn't interfere (well, it still doesn't work when I turn it off), and canyouseeme.org says that it can establish a connection to my chosen port when the server runs.
Here is the source code for the server, since I figured out it was possible to just go via the command line with a little telnetting.
When I try to establish a connection, it just says Could not open connection to the host, on port 49163:Connection failed
Server:
import java.net.*;
import java.io.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket server = null;
try {
System.setProperty("java.net.preferIPv4Stack" , "true");
server = new ServerSocket(49163);
} catch (IOException e) {
System.err.println("Could not listen on port: 49163.");
System.exit(1);
}
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(newInputStreamReader(client.getInputStream()));
String inputLine;
String outputLine;
out.println("Connection established");
while ((inputLine = in.readLine()) != null) {
if (inputLine.equals("exit")) {
break;
}
outputLine = inputLine;
out.println(outputLine);
}
out.close();
in.close();
client.close();
server.close();
System.out.println("Server offline");
}
}
Oh yeah, preferIP4vStack was something I picked up on Stackoverflow, but it doesn't seem to work for me.
For some reason I'm not able to inlcude the code for the client, I keep getting messages about formatting, and I just can't figure it out. But the way I see it is that I'm not even able to connect via the command line (when I try to connect to the "real" IP), so the client doesn't have to get involved. But for you who want to see the error anyway:
java.net.ConnectException: Connection refused: 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.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at ChatClient.main(ChatClient.java:12)
Could not open connection to the host, on port 49163:Connection failed
No it didn't. Thats not a Java message. Your code said that, when you caught a ConnectException that had a much more detailed message of its own. Print that and you might have some hope of finding what went wrong. Making up your own messages and suppressing what the exception tells you is rarely if ever a good idea.
The message will probably be one of:
'connection refused', which means you got the target host or port wrong, or there is a firewall
'connection timed out', which is a network connectivity problem
'no route to host', which is an IP routing problem
'unknown host', which again means you got the server name wrong.
I don't know if I'm suposed to laugh or cry now.
A friend told me that MAYBE, maybe the problem might be that I try to log in with the external IP from a network-intern PC, which for some mysterious reason can't get out or can't get back in.
Got someone to try and login from somewhere else, and voila! Works like a charm.

java.net.ConnectException

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.

ObjectInputStream.readObject() hangs forever during the process of socket communication

I have encountered a problem of socket communication on linux system, the communication process is like below: client send a message to ask the server to do a compute task, and wait for the result message from server after the task completes.
But the client would hangs up to wait for the result message if the task costs a long time such as about 40 minutes even though from the server side, the result message has been written to the socket to respond to the client, but it could normally receive the result message if the task costs little time, such as one minute. Additionally, this problem only happens on customer environment, the communication process behaves normally in our testing environment.
I have suspected the cause to this problem is the default timeout value of socket is different between customer environment and testing environment, but the follow values are identical on these two environment, and both Client and server.
getSoTimeout:0
getReceiveBufferSize:43690
getSendBufferSize:8192
getSoLinger:-1
getTrafficClass:0
getKeepAlive:false
getTcpNoDelay:false
the codes on CLient are like:
Message msg = null;
ObjectInputStream in = client.getClient().getInputStream();
//if no message readObject() will hang here
while ( true ) {
try {
Object recObject = in.readObject();
System.out.println("Client received msg.");
msg = (Message)recObject;
return msg;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
the codes on server are like,
ObjectOutputStream socketOutStream = getSocketOutputStream();
try {
MessageJobComplete msgJobComplete = new MessageJobComplete(reportFile, outputFile );
socketOutStream.writeObject(msgJobComplete);
}catch(Exception e) {
e.printStackTrace();
}
in order to solve this problem, i have added the flush and reset method, but the problem still exists:
ObjectOutputStream socketOutStream = getSocketOutputStream();
try {
MessageJobComplete msgJobComplete = new MessageJobComplete(reportFile, outputFile );
socketOutStream.flush();
logger.debug("AbstractJob#reply to the socket");
socketOutStream.writeObject(msgJobComplete);
socketOutStream.reset();
socketOutStream.flush();
logger.debug("AbstractJob#after Flush Reply");
}catch(Exception e) {
e.printStackTrace();
logger.error("Exception when sending MessageJobComplete."+e.getMessage());
}
so do anyone knows what the next steps i should do to solve this problem.
I guess the cause is the environment setting, but I do not know what the environment factors would affect the socket communication?
And the socket using the Tcp/Ip protocal to communicate, the problem is related with the long time task, so what values about tcp would affect the timeout of socket communication?
After my analysis about the logs, i found after the message are written to the socket, there were no exceptions are thrown/caught. But always after 15 minutes, there are exceptions in the objectInputStream.readObject() codes snippet of Server Side which is used to accept the request from client. However, socket.getSoTimeout value is 0, so it is very strange that the a Timed out Exception was thrown.
{2012-01-09 17:44:13,908} ERROR java.net.SocketException: Connection timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:146)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:312)
at sun.security.ssl.InputRecord.read(InputRecord.java:350)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:809)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:766)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:94)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:69)
at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2265)
at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2558)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2568)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1314)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
so why the Connection Timed out exceptions are thrown?
This problem is solved. using the tcpdump to capture the messages flows. I have found that while in the application level, ObjectOutputStream.writeObject() method was invoked, in the tcp level, many times [TCP ReTransmission] were found.
So, I concluded that the connection is possibly be dead, although using the netstat -an command the tcp connection state still was ESTABLISHED.
So I wrote a testing application to periodically sent Testing messages as the heart-beating messages from the Server. Then this problem disappeared.
The read() methods of java.io.InputStream are blocking calls., which means they wait "forever" if they are called when there is no data in the stream to read.
This is completely expected behaviour and as per the published contract in javadoc if the server does not respond.
If you want a non-blocking read, use the java.nio.* classes.

Categories

Resources