Reputation: 107
I have created a socket that connects to a Raspberry pi hot spot. I am able to successfully connect to it and send a string to the pi. However, since I have tried to implement read functionality to get data from the pi, I have had some issues.
Every time I run the while loop or just have a "response = myBufRead.readLine()", the program stalls.
private class StatusCheck extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//debug vibrations and text
if(vibrate) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(100);
}
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d(debugStr, "In initial connect");
mySocket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (mySocket == null) {
str1 = "Socket became null";
return null;
}
str1 = "Connected";
try {
PrintWriter myPrintWriter = new PrintWriter(mySocket.getOutputStream(), true);
InputStreamReader myInputStreamRead = new InputStreamReader(mySocket.getInputStream());
BufferedReader myBufRead = new BufferedReader(myInputStreamRead);
Log.d(debugStr, "In out created");
myPrintWriter.write(recordName);
Log.d(debugStr, String.valueOf(myBufRead.ready()));
Log.d(debugStr, "About to enter while loop");
while((response = myBufRead.readLine()) != null) {
Log.d(debugStr, "in while loop");
response = myBufRead.readLine();
Log.d(debugStr, String.valueOf(myBufRead.ready()));
Log.d(debugStr, myBufRead.readLine());
Log.d(debugStr, String.valueOf(myBufRead.ready()));
}
Log.d(debugStr, "out of while loop");
myPrintWriter.close();
myInputStreamRead.close();
myBufRead.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
}
Anyone know why this is happening? Any help is appreciated, thanks!
Upvotes: 1
Views: 95
Reputation: 3664
BuffereadReader.readLine()
is a blocking method, so it will wait and, as you say, "stall" its thread until it has something to read. Are you calling flush()
after you write to the stream from your pi?
Another issue might be that readLine()
will wait for a complete line, i.e. it will wait until it reads a line separator character. Are you sending a line separator character from your pi? See Socket Multithreading - Reading input stream pauses thread
You can do (from the pi end, assuming you're using a BufferedWriter
):
bufferedWriter.write(text);
bufferedWriter.newLine();
bufferedWriter.flush();
Upvotes: 2