jhunters / jprotobuf

A useful utility library for java programmer using google protobuf
Apache License 2.0
890 stars 282 forks source link

关于servlet 响应数据问题 #33

Closed Rekoe closed 9 years ago

Rekoe commented 9 years ago

在servlet 返回中调用

OutputStream out = resp.getOutputStream();
codec.writeTo(obj, CodedOutputStream.newInstance(out));

返回的数据是空的

但调用客户端是可以得到返回值的

OutputStream out = resp.getOutputStream();    
out.write(codec.encode(obj));

是不是codec.writeTo 方法有问题?

xiemalin commented 9 years ago

能否在客户端 用 writeTo方法测试一下,还有你使用的版本是? OutputStream out = resp.getOutputStream(); codec.writeTo(obj, CodedOutputStream.newInstance(out));

Rekoe commented 9 years ago

1.7.9

Rekoe commented 9 years ago
public class UserJProtoBufProtoClass {

    @Protobuf(fieldType = FieldType.INT64, order = 1, required = false)
    public Long id;
    @Protobuf(fieldType = FieldType.STRING, order = 2, required = false)
    public String name;
    @Protobuf(fieldType = FieldType.OBJECT, order = 4)
    public PhoneNumberJProtoBufProtoClass phone;

    public static class PhoneNumberJProtoBufProtoClass {
        @Protobuf(fieldType = FieldType.STRING, order = 1, required = true)
        public String number;
    }
}
    public static void main(String[] args) throws IOException {
        UserJProtoBufProtoClass udbp = new UserJProtoBufProtoClass();
        udbp.id = System.currentTimeMillis();
        udbp.name = "lisi";
        Codec<UserJProtoBufProtoClass> codec = ProtobufProxy.create(UserJProtoBufProtoClass.class);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //byte[] bytes = codec.encode(udbp);
        //out.write(bytes);

        codec.writeTo(udbp, CodedOutputStream.newInstance(out));

        UserJProtoBufProtoClass tem =codec.decode(out.toByteArray());
        System.out.println(Json.toJson(tem.id));

    }

确实有问题

xiemalin commented 9 years ago

经测试,代码没有问题,应该你的使用API有问题 google的 protocol buffer 代码 CodedOutputStream.newInstance(out) 是不会自动回写到 out对象中的,所以你需对CodedOutputStream进行一下手工 flush. 代码如下:

        OutputStream os = new ByteArrayOutputStream();
        CodedOutputStream newInstance = CodedOutputStream.newInstance(os);
        codec.writeTo(newPojo, newInstance);
        newInstance.flush();
        System.out.println(os.toString());
Rekoe commented 9 years ago

嗯 感谢