Re: Java (android) socket reconnection
Thank You very much! Honestly.
I started analyze Your code but it is partly to hard for me - I'm newbe in Java and it gives me error on invoking method "getWriter" in line:
Writer w = connector.getWriter()
and further exactly inside this method in line "else if( ! socket.isClosed() )". I'm going fight with this in next hours, and don't give up.
One hour ago I write my code as simple as I can and in one thread - everything to avoid problem with synchronization. Effect on the server is still the same (several connection attempts after starting server when client was waiting for it)
I apologize that I'm putting my code again (I hope in good format) instead try to adapt new one from You immediately, but I want to understand this problem.
thrd3 = new Thread(new Runnable() {
@Override
public void run() {
Socket sock = null;
BufferedWriter out = null;
while (true) {
//time to rest for system
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
}
//attempt to send data
if (sock != null) {
try {
out.write("TEST DATA\n");
out.flush();
} catch (IOException e) {
//catch the error
// ERROR-----------------------
try {
out.close();
sock.close();
sock = null;
} catch (IOException e1) {
sock = null;
out = null;
}
}
} else
// if socket is null try to connect again (or firs time)
{
try {
sock = new Socket();
sock.connect(new InetSocketAddress(address,
5000), 1000);
out = new BufferedWriter(
new OutputStreamWriter(sock
.getOutputStream()));
} catch (IOException e1) {
sock = null;
}
}
}
}
});
thrd3.start();
Best regards,
Artik