Reputation:
I have a little problem with a Socket. So, code is below:
private class SocketThread extends Thread {
String whatistodo;
public SocketThread(String whatistodo) {
this.whatistodo = whatistodo;
}
@Override
public void run() {
try {
Socket socket = new Socket(IP (is set), port (is set)); // Eröffne Socket
if(whatistodo.equals("read")) {
Boolean isDone = false;
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); // In Buffer
String msg;
while (!isDone && ((br.readLine()) != null)) {
// stuff
System.out.println(msg);
}
}
if(whatistodo.equals("close")) {
socket.close();
if(socket.isClosed()) {
finish();
}
}
Log.d("Socket", String.valueOf(socket.isClosed()));
} catch (IOException e1) {
/* Log.e("IOException", String.valueOf(e1));
Looper.prepare();
new AlertDialog.Builder(Bedienung.this)
.setTitle("Socketfehler")
.setMessage("Verbindung mit TCP fehlgeschlagen / verloren.")
.setPositiveButton("Ok", null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Looper.loop(); */
}
}
}
I call the class SocketThread with the function connectToSocket();
There's one string parameter called "whatistodo".
The parameter can be "read" or "close"
protected Boolean connectToSocket(String whatistodo) {
Thread obj = new SocketThread(whatistodo);
obj.start();
return false;
}
The function connectToSocket("read")
is called if there's a internet connection.
The function connectToSocket("close")
is called by onBackPressed
.
But after closing the socket, I'm still receiving messages.
How to solve this?
Greetings, Baldoius
Upvotes: 0
Views: 46
Reputation: 97168
Every time you create your SocketThread, it creates a new socket. If "whatistodo" is set to "close", it will create a new socket and close it immediately. The thread created with "whatistodo" equal to "read" has its own socket, so it will continue running and reading from it.
You need to ensure that all of your threads share the same socket instance.
Upvotes: 1