Android client - Java server, Socket won't throw exception - java

I'm trying to connect my Android APP to a Java server that I've made for it.
I have a problem, the server works good and the APP works fine too when connected to the server.
The problem comes when I close the server and try to connect to it. The suppose is that the Socket.connect() would throw an exception that I would catch, but this exception is not thrown.
I don't know what I'm doing bad, I paste my code here for you to read and maybe somone can help me. Thanks for all mates :D
Connection attributes:
static Socket s;
static DataOutputStream output;
static boolean connected;
The method who needs the connection:
public void enviarDatos(int r, int g, int b){
connect();
if(connected){
panel.setText(panel.getText() + "\nEnviando datos...");
try {
output.writeUTF(r + "," + g + "," + b);
} catch (Exception e) {
panel.setText("Error: " + e.getMessage());
}
disconnect();
}
}
The methods to connect and disconnect are there:
public void connect(){
try {
s = new Socket();
int timeout = 1000;
s.connect(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT), timeout);
output = new DataOutputStream(s.getOutputStream());
connected = true;
panel.setText("Conexion exitosa.");
} catch (Exception e) {
connected = false;
panel.setText("Error: " + e.getMessage());
}
}
public void disconnect(){
try{
output.close();
s.close();
connected = false;
} catch(Exception e){
panel.setText("Error: " + e.getMessage());
}
}

The first connect() method is different from the one you posted in the large code block where you present both the methods. It's pretty unclear which one you are using to connect. Try adding the int timeout parameter to the connect() like this:
int timeout = 1000; // 1s timeout
s.connect(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT), timeout);
This should make connect throw an IOException after the timeout expires.
Hope this solves your problem.

I see one potential issue in "disconnect". I think you're trying to close the socket when the output stream is still opened. In this case, the socket may not close properly which may cause issues in reopening. Although you should see an exception being thrown during closing.
In disconnect(), can you try closing output first before closing the socket?
public void disconnect(){
try{
output.close();
s.close();
connected = false;
} catch(Exception e){
panel.setText("Error: " + e.getMessage());
}
}
I don't have the context of this problem, but that's one potential issue I saw. Hopefully it helps.

Related

Trying to Get a new ServerSocket to open fails

I was given the below code by my teacher for a class. I ran it one or twice and it worked fine. However I suddenly cannot get it to run from the command prompt on Windows 8 anymore. No matter what port I specify it just prints "Opening port..." and never continues. No exception is ever thrown. I have disabled my firewall and antivirus and it does not seem to work. I have added a print statement as the first line of the try catch block and it will print but it just will not create the new Socket. I am sure it is something in my Windows settings but I am unsure as to what or how to resolve it.
// Server program
// File name: "TCPServer.java"
import java.io.*;
import java.net.*;
public class TCPServer
{
private static ServerSocket servSock;
public static void main(String[] args)
{
System.out.println("Opening port...\n");
try{
// Create a server object
servSock = new ServerSocket(Integer.parseInt(args[0]));
}
catch(IOException e){
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
run();
}while (true);
}
private static void run()
{
Socket link = null;
try{
// Put the server into a waiting state
link = servSock.accept();
// Set up input and output streams for socket
BufferedReader in = new BufferedReader(new InputStreamReader(link.getInputStream()));
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
// print local host name
String host = InetAddress.getLocalHost().getHostName();
System.out.println("Client has estabished a connection to " + host);
// Receive and process the incoming data
int numMessages = 0;
String message = in.readLine();
while (!message.equals("DONE"))
{
System.out.println(message);
numMessages ++;
message = in.readLine();
}
// Send a report back and close the connection
out.println("Server received " + numMessages + " messages");
}
catch(IOException e){
e.printStackTrace();
}
finally{
try{
System.out.println("!!!!! Closing connection... !!!!!\n" + "!!! Waiting for the next connection... !!!");
link.close();
}
catch(IOException e){
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
This code works fine. The problem is the code for the client. The answer to your problem is already written in a comment in your code.
// Put the server into a waiting state
link = servSock.accept();
The server goes into a waiting state until it gets a connection. The client is the one that would be getting the error since it did not connect. If the client was working correctly the code would continue and you would get the additional output.

Java: Socket closing after try-catch blocks

I am attempting a client/server type chat box (using GUI's). I won't get into details of the multi-threading I used in the program since I believe it is not part of the problem (I hope not) and it will be good amount of code to post. Anyways, for both my client and my server I create a socket, and some other stream classes within a try block, and some reason the sockets close after the catch blocks. PS I do NOT call socket.close() method anywhere that could end if early
Server, this is ran into a constructor of one of my class. It breaks down into, my main has the actually server stuff on a different thread, (like my previous post) it is a fix so that the gui can load and run the server stuff without one waiting on the other. Anyways, without all that detail, here is my code
public ChatAppProtocol(Socket sock)
{
super("ChatAppServer");
// this also has a clas var of Socket
this.sock = sock;
try (
PrintWriter output = new PrintWriter(this.sock.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(this.sock.getInputStream())) ;
)
{
// first stream of a string is the username loging in from client
String name = input.readLine();
// this returns false, so its not closed
System.out.println("closed?: " + this.sock.isClosed());
}
catch (IOException e)
{
e.printStackTrace();
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// closed after the catch blocks before methods even ends
// p.s. i also plan on using the socket in another method but can't since it closes
System.out.println("closed?: " +this.sock.isClosed());
}
now my client
#FXML
private void login()
{
this.name = this.username.getText().trim();
this.portnum = Integer.parseInt(this.port.getText());
this.name = this.username.getText().trim();
this.ipaddr = this.ip.getText().trim();
try (t
Socket socket = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
)
{
this.sock = socket;
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// returns true here, closes before methods end and i cant reuse it
System.out.println("IS IT CLOSED!!!!!! " + this.sock.isClosed());
}
}
so, any reason why both this different class, different files, different project sockets close after try-catch blocks? Can't find answer online, and been on it for a while and I am stuck. I found out about this problem after seeing this on the server side console
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:943)
at chatappserver.ChatAppProtocol.run(ChatAppProtocol.java:62)
Because you're creating socket with the brackets of the try block, it is automatically closed upon exiting the block. Instead, try creating it inside the block itself and it shouldn't be closed:
try {
this.sock = new Socket(this.ipaddr, this.portnum);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println(this.name);
} catch (UnknownHostException e) {
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
}
// this.sock should still be open at this point.
Have a read of the Java tutorial on try-with-resources for more information on why you're getting your current behaviour.
You are using try-with-resources, which is roughly an equivalent of:
try
{
this.sock = new Socket(this.ipaddr, this.portnum));
output.println(this.name);
// this returns false, not closed
System.out.println("closed?: " +this.sock.isClosed());
}
catch (UnknownHostException e)
{
System.err.println("Problem at ip: " + this.ipaddr);
System.exit(1);
} finally {
if (this.sock != null)
this.sock.close();
}
Just initialize the socket outside the resources clause of try (...) and it won't get closed

My socket keeps closing after socket.connect times out

This is driving me insane!
I'm trying to implement TCP holepunching and as part of this I have a socket trying to connect continuously.
For some reason, after the first mobileSocket2.connect call times out, the second time a socket closed exception comes up. I have no idea why. As far as I can tell, a connection timeout shouldn't close the socket. so why does it say socket closed the second loop?
I bind a socket to the same local IP address and local port earlier on but close that socket.
Any help would be greatly appreciated.
Socket mobileSocket2 = new Socket();
try {
System.out.println("105");
mobileSocket2.setReuseAddress(true);
System.out.println("109");
mobileSocket2.setSoTimeout(50);
mobileSocket2.bind(new InetSocketAddress(myIPAddress.getHostAddress(), myPort));
System.out.println("bound");
}
catch (Exception e) {
System.out.println("caught 104: " + e.toString());
}
while(true){
Thread.sleep(5000);
try{
System.out.println("124");
mobileSocket2.connect(new InetSocketAddress(mobileAddress.getHostAddress(), mobilePort));
System.out.println("connection made: " + mobileSocket);
}
catch(Exception e){
System.out.println("exception 2 caught " + e.toString());
}
}
Your code is invalid.
You can't reconnect a connected Socket. When the connect succeeds you need to add a break statement.
You can't reuse a Socket when a connect() has failed. You have to close it and create a new one.
Either reopen the socket when the first exception is caught, or set the timeout to 0, which the javadoc says it is interpreted as 'infinite'. I didn't look at the Socket and SocketImpl code, but I'm fairly confident that, since Socket is a Closeable (and also an AutoCloseable), the implementation is along the lines of
public void connect(InetAddress address, int port) throws IOException {
try {
// connect to the other endpoint
} catch(/*any relevant exception*/) {
throw new IOException(/* ... */);
} finally {
this.close();
}
}

Java - TCP exception

I have a TCP Server and Client both written in Java and running on separate machines on Rhel 5.3 with jdk1.6. I have handled pretty much all the methods i could find to detect a disconnection on the "Server".
Following is a snippet of the Server code
private void listenforConnection() {
try {
socket = serverSocket.accept();
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
socket.setSoTimeout(5);
bosTcpOutStream = new BufferedOutputStream(socket.getOutputStream());
bisTcpInStream = new BufferedInputStream(socket.getInputStream());
log("New connection accepted from " + socket.getRemoteSocketAddress().toString());
sendHeartBeatsToClient();
} catch (IOException ie) {
log("Listener IOException : " + ie.getMessage());
}
}
private void sendHeartBeatsToClient() {
try {
while (true) {
long lngCurrentMillis=System.currentTimeMillis() ;
if ((lngCurrentMillis - lngLastSentMessageTime) >= 5000) {
byte[] bHeartBeat = getHeartBeatMessage();
bosTcpOutStream.write(bHeartBeat);
bosTcpOutStream.flush();
lngLastSentMessageTime = System.currentTimeMillis();
log("Heartbeat sent.");
} else {
try {
if (bisTcpInStream.read() == -1) {
log("Read Input Stream returned -1");
break;
}
} catch (SocketTimeoutException se) {
//Do nothing as i am not expecting the client to send anything.
} catch (IOException e) {
log("Read Input Stream error - " + e.getMessage());
break;
}
}
Thread.sleep(1);
}
} catch (IOException e) {
disconnectClientAndCloseSocket();
log("IO Exception" +e.getMessage());
} catch (InterruptedException e) {
disconnectClientAndCloseSocket();
log("Thread interrupted terminating." + e.getMessage());
}
}
I have also modified the tcp-keepalive kernel parameters on the "Server" machine as below:
net.ipv4.tcp_keepalive_time=2
net.ipv4.tcp_keepalive_probes=1
net.ipv4.tcp_keepalive_intvl=2
Now when i am simulating a disconnection by unplugging the network cable of the Client machine(after it has established the connection and received the initial data from the Server), I am seeing two different outcomes which i am unable to understand:-
If i unplug the cable after 10 to 15 seconds of successful client connection. On the "Server" I receive an IO Exception with "no route to host" after 10 minutes of unplugging the cable.
If i unplug the cable after 60 or so seconds of successful client connection. On the "Server" an IO exception is thrown with "Connection timed out" within 10 seconds. This is valid behavior keeping in mind the keep alive settings.
I have tried this a couple of times and i always get the same result.
What i don't understand is why the first outcome takes 10 minutes and it doesn't behave like the second outcome. Am i missing something?

Socket connection doesn't time out

I'am trying to set a timeout when a client try to connect to a server, if the server is down, the connection will wait 10 sec befor throwing the timeout exception.
In my case the code bellow throw the IOException without waiting, I really don't get it !
public boolean establishConnection()
{
System.out.println ("Connecting to " +
this.getServerHostname() + " au port " + this.getServerPort()+ " ...");
try {
SocketAddress sockaddr= new InetSocketAddress(_serverHostname, _serverPort);
_echoSocket = new Socket();
_echoSocket.connect(sockaddr,10000);
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown Host: " + this.getServerHostname());
return false;
} catch (SocketTimeoutException e) {
System.err.println("Timeout");
return false;
} catch (IOException e) {
System.err.println("IOException : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
You'll only get a timeout if your connection request is not answered. If the server immediately rejects it, or if the server doesn't exist, you'll get an exception immediately.
But is this what you want to achieve?
If your intention is, in case the server is temporarily down, then try again after 10 sec then your approach is wrong.
You should try to do a connection to the server and if you get an exception because the server is down, you can sleep for 10 seconds and try the request again.
Otherwise Ernest's answer is correct

Categories

Resources