java NIO 传对象

java NIO 传对象

//Client 端:
  Student pgt=new Student();
  pgt.setName("name");
  pgt.setAge("age");
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  oos.writeObject(pgt);
  oos.close();
  byte[] bs = baos.toByteArray();
  ByteBuffer buffer = ByteBuffer.wrap(bs, 0, bs.length);
  
    while (buffer.hasRemaining() & client.write(buffer) != -1)
    {
       waitFor(1000);
    }
    buffer.flip();

//Server 端:
       int reads = sc_key.read(byteBuffer);
       byteBuffer.flip();
       byte[] tmp_buffer = byteBuffer.array();
       ByteArrayInputStream byteIn = new ByteArrayInputStream(tmp_buffer);
       ObjectInputStream objIn = new ObjectInputStream(byteIn);
       pgt = (Student) objIn.readObject();
       objIn.close();

你可能感兴趣的:(java NIO 传对象)