how to read socket input stream in Android
can anybody tell me how to read socket input stream. Here is my code.
if (!serverIpAddress.equals(""))
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.i("ClientActivity", "Connecting...");
Socket socket = new Socket(serverAddr, 5777);
try {
Log.i("ClientActivity", "Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("<maplist />");
Log.i("ClientActivity", "Sent.");
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
buffer = new StringBuilder();
new Thread(new Runnable() {
@Override
public void run() {
try
{
buffer.append(input.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
this.Writ开发者_如何学GoeXMLResponse(buffer.toString());
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
In my code and in run method where i am reading the input Stream a exception occurs. which says java.net.socketException: bad file number.
and if i use while loop my app freezes. any suggestion will be appretiative. thanks
It's a little bit hard to tell what's going on without seeing more of your code, but here's my deduction of what's going on here (I've done quite a bit of socket programming in android apps):
You're creating the Socket and wrapping the input stream in a BufferedReader on the application's main thread and then constructing a new thread to wait until you get input on the socket and subsequently process that input. However, when you create the new thread, that code goes to execute in the background, and in the meantime the method that all this is happening in (the method where you're declaring the Socket and BufferedReader) is finishing! When that method finishes, there is no more reference to the Socket, so it's closed and garbage-collected by the runtime. Unfortunately, your background thread has no idea that it's socket has been closed in the meantime, so it's readLine() ends up throwing an exception stating that the socket (fileno, unix-wise) is now "bad" since it was closed by the runtime.
You were somewhat right in initially assuming that a while loop might fix it, and it would, because it wouldn't allow the method to finish, thereby keeping the Socket open, but the problem is that the entire UI freezes while your app is waiting for input from the socket.
The true solution to this is to do all your socket communication in a Service running on a separate thread from the UI of the application.
I did my best to explain this, but if any parts aren't clear, just comment, and I'll try and explain further or give you more specific help.
精彩评论