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();//关闭输出流

这句话也得去掉的,要不然也会报错:输出流已经关闭。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值