问题
Hi guys so I have a task where I'm suppose to send a message to a server, and then get a reply back. I keep getting failed 1recvfrom failed: EBADF (Bad file descriptor)
error and I'm new to this socket stuff. Hopefully someone can help me out. Here's my async task:
private class SendDataAsyncTask extends AsyncTask<Void,Void,Void>
{
private String reply = "";
@Override
protected Void doInBackground(Void... params)
{
try {
Socket socket = new Socket("ip",portNumber);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
//printWriter.write("hello there");
printWriter.println("hello there");
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printWriter.flush();
reply = bufferedReader.readLine();
if(reply != null && !reply.equals(""))
{
Log.d(SOCKET_TESTING_TAG,"my message is " + reply);
}
else
{
Log.d(SOCKET_TESTING_TAG,"no message yet");
}
Log.d(SOCKET_TESTING_TAG,"break 3");
printWriter.close();
}
catch (IOException e)
{
Log.d(SOCKET_TESTING_TAG,"failed " + e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
public void onPostExecute(Void var)
{
tv_response.setText(reply);
}
}
- Note: When I put the if statement to check for the null readline before
printWriter.flush()
I still get an error.
回答1:
printWriter.close();
Closing the input or output stream of a socket closes the other stream and the socket. Remove both occurrences.
if(bufferedReader.readLine() != null)
This doesn't make sense. You are throwing the line away and then reading the next line if it wasn't null. You need to store the result into a variable.
You probably need to use printWriter.println()
instead of printWriter.write()
. Probably the peer is reading lines too, and you aren't sending one (no line terminator).
If reply == null
it means the peer has closed the connection. Not 'no message yet'. An empty string may be a protocol error but it also is not 'no message yet'.
来源:https://stackoverflow.com/questions/47899231/how-to-use-socket-to-send-and-receive-message-from-server