Android错误:读取bufferedreader后连接重置

时间:2019-07-02 04:33:13

标签: java android sockets bufferedreader

我在我的android应用中使用了名为registerDevice()的方法 代码以发送和接收包含多行的特定数据。但我不断收到此错误:

  

W / System.err:java.net.SocketException:连接重置

public void registerDevice(){
    final Handler handler = new Handler();
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                Socket s = new Socket(gateway, 1234);
                OutputStream out = s.getOutputStream();
                PrintWriter output = new PrintWriter(out);
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                output.println("hello world\r\n");
                output.flush();
                StringBuffer stringBuffer = new StringBuffer("");
                String line = null;
                while ((line = input.readLine()) != null) {
                    stringBuffer.append(line);
                }
                final String st = line.substring(5);
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        if (st.trim().length() != 0)
                            Toast.makeText(getApplicationContext(),st,Toast.LENGTH_LONG).show();
                    }
                });

                output.close();
                out.close();
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
}

更新:我将代码更改为此:

                Socket s = new Socket(gateway, 1234);
                OutputStream out = s.getOutputStream();
                PrintWriter output = new PrintWriter(out);
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                output.println("hello world\r\n");
                output.flush();
                final String st = input.readLine();
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        if (st.trim().length() != 0)
                            Toast.makeText(getApplicationContext(),"st",Toast.LENGTH_LONG).show();
                    }
                });

                output.close();
                out.close();
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

我仍然在“最终字符串st = input.readLine();”上遇到异常线。我应该从服务器获取一个MAC地址,然后服务器关闭连接。我检查了服务器,发现它没有问题,它在向我发送了MAC之后关闭了连接。

1 个答案:

答案 0 :(得分:0)

伙计们,我发现了问题,这是我发送的数据包,我只是将outout.println()更改为output.write(),所以现在服务器识别了我的命令并发送了我需要的数据,这导致了我的输入流不为空,并避免出现异常。