版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34709057/article/details/83651842
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();//关闭输出流
这句话也得去掉的,要不然也会报错:输出流已经关闭。