public void writeResponsePacket(SocketChannel socketChannel, ResponsePacket responsePacket) { try { ByteBuffer byteBuffer; byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] marshalObject = MarshalHelper.objectToBytes(responsePacket); byte[] marshalHeader = MarshalHelper.int32ToBytes(marshalObject.length); byteBuffer.clear(); byteBuffer.put(marshalHeader); byteBuffer.put(marshalObject); byteBuffer.flip(); // If no connection now, please ignore it (usually in async calling) try { if (socketChannel.isConnected()) { socketChannel.write(byteBuffer); } } catch (IOException e) { socketChannel.close(); } } catch (IOException e) { e.printStackTrace(); } }