How to use socket to send and receive message from server?

谁都会走 提交于 2019-12-13 03:07:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!