1. 程式人生 > >java.net.SocketException: Socket is closed

java.net.SocketException: Socket is closed

 String TAG = "ggg";
    Socket socket;
    InputStream is;
    OutputStream os;

    private void initcli() {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress("127.0.0.1", 18888), 5000);//設定連線請求超時時間10 s
            // 設定 socket 讀取資料流的超時時間
//            socket.setSoTimeout(5000);
            //2.獲取輸出流用來向伺服器端傳送登陸的資訊
            os = socket.getOutputStream();//位元組輸出流
            byte[] bb = new byte[]{0x21, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00};
            os.write(bb);
            //0x21,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00 獲取裝置名稱
            //0x21,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x12,0x00,0x01,0x00,0x03,0x00,0x03   設定碰撞靈敏度
            //0x21,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00  獲取設定
            Log.i(TAG, "initcli:傳送請求: " + Arrays.toString(bb) + "        ");
            os.flush();
            socket.shutdownOutput();//關閉輸出流
            //3.獲取輸入流,用來讀取伺服器端的響應資訊
            is = socket.getInputStream();
            byte[] bt = new byte[16];
            is.read(bt);
            Log.e(TAG, "initcli:請求迴應: " + Arrays.toString(bt));

            StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < bt.length; i++) {
                hexString.append("0x");
                if ((bt[i] & 0xff) < 0x10)//0~F前面不零
                    hexString.append("0");

                hexString.append(Integer.toHexString(0xFF & bt[i]) + " ");
            }
            Log.e(TAG, "initcli:======================= " + hexString.toString().toLowerCase());


            //4.關閉其他相關資源
            is.close();
            os.close();
//            socket.close();
            Log.i(TAG, "initcli: ============");
        } catch (IOException e) {
            Log.e(TAG, "initcli:error ");
            e.printStackTrace();
        }finally {
            while (true) {
                try {
                    Thread.sleep(2000);
                    is = socket.getInputStream();
                    byte[] bt = new byte[16];
                    is.read(bt);
                    Log.e(TAG, "initcli:請求迴應: " + Arrays.toString(bt));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

想在is或者os close後還想看看後面還有沒有接收到其他資料就報錯了。所以得is.close()和os.close兩個都得註釋掉才不會報錯。還有如果後面要給服務端傳送資料的話 

socket.shutdownOutput();//關閉輸出流

這句話也得去掉的,要不然也會報錯:輸出流已經關閉。