无法在android中获得TCP响应

时间:2015-01-21 23:51:09

标签: android sockets tcp timeout

代码应该作为客户端连接到TCP服务器,发送命令并接收响应。

代码连接并发送命令但是在" socket.getInputStream()"中超时,即使连接的服务器收到命令并且应该响应(使用TCP检查) PC上的客户端程序。)

这是任务的代码:

public class MyClientTask extends AsyncTask<Void, Void, Void> {

    String dstAddress;
    int dstPort;
    String command;
    String response = "";

    MyClientTask(String addr, int port, String cmd){
        dstAddress = addr;
        dstPort = port;
        command = cmd;
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        Socket socket = null;
        InputStream inputStream;

        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(dstAddress, dstPort),2000);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];
            int bytesRead;

            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
            out.println(command);

            inputStream = socket.getInputStream();
            socket.setSoTimeout(20000);
            while ((bytesRead = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }

        }catch (UnknownHostException e){
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } catch (Throwable e) {
            e.printStackTrace();
            response = "Throwable: " + e.toString();
        }finally{
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        textResponse.setText(response);
        super.onPostExecute(result);
    }

}//MyClientTask

1 个答案:

答案 0 :(得分:0)

您正在阅读回复,直到结束。在对等体关闭连接之前,流的结束不会发生。你有一个读取超时: ergo,可能,他没有关闭连接。否则你的超时太短了。两秒钟并不多。

您需要一种正确的方式来阅读响应,或者在它们到达时处理这些部分。