Reputation: 68
I am trying to work with sockets in android programming, sending to the server works fine but i have problems with receiving a string from the server.
the socket is connected, but if the server is sending a string the android app only prints out: java.io.BufferedReader@418daee0
i dont know what that mean..is it an error or something like that?
this is my code: Maybe someone could help me a little bit to get that work.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 2000;
private static final String SERVER_IP = "192.168.1.1";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String test = br.toString();
TextView message = (TextView) findViewById(R.id.received);
message.setText(test);
//in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Upvotes: 0
Views: 2795
Reputation: 44813
what you need to do is read from the BufferedReader
. Currently you are just printing the br
object.
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine ()) != null) {
System.out.println (line);
}
as per the javadocs readLine
will return null if the end of the stream has been reached
Upvotes: 1
Reputation: 26198
problem:
String test = br.toString();
You are basically referencing the memory location in string form of the br
object thus printing the memory location in your TextView
. What you need to do is to read the inputStream from the socket connection of the server from your BufferedReader
object.
solution:
String test = br.readLine();
The readLine
method will wait for the response of the server from the InputStream
where the socket is connected. Now the above will only get one line of response from the server if the server sends multiple line then you put it in a while loop.
Upvotes: 1