Hi this is my code for sending data through a socket to another device connected to the network
try {
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
printWriter.print(data);
Log.d("error", printWriter.checkError() + "");
printWriter.flush();
} catch (IOException e) {
Log.d("socket","is disconnected");
e.printStackTrace();
}
the problem is printWriter.checkError()
is always returning false
and the IOException
never happens. for disconnecting socket I'm turning device off and trying to send data again. even reading from InputStream
doesn't help
private class SocketHandler extends AsyncTask<Void, byte[], Void> {
InputStream in;
@Override
protected void onPreExecute() {
try {
in = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
byte[] content = new byte[2048];
if (in != null) {
while (true) {
try {
if (in.available() > 0) {
int n = in.read(content);
if (n == -1) {
break;
}
publishProgress(new byte[][]{Arrays.copyOfRange(content, 0, n)});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onProgressUpdate(byte[]... values) {
String data = new String(values[0]);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void aVoid) {
Log.d("socket", "is disconnected");
}
}
read
never returns -1
so I can detect the socket is disconnected. What can I do?
edit: It's not duplicate of JAVA : Handling socket disconnection because I did everything mentioned there