netty长字符串传送问题
最近有个socket通信项目,我用了netty,可是后来发现传送字符串过长时,字符被截了,
后来一查发现有LengthFieldBasedFrameDcoder这个encode,可是用了出错,我的要求是
传输时用字符串
以下是我改了之后的代码:
1./**
2. * 消息解码器
3. *
4. */
5.public class MessageDecoder extends LengthFieldBasedFrameDecoder {
6.
7. public MessageDecoder(int maxFrameLength, int lengthFieldOffset,
8. int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {
9.
10. super(maxFrameLength, lengthFieldOffset, lengthFieldLength,
11. lengthAdjustment, initialBytesToStrip);
12. }
13.
14. @Override
15. protected Object decode(ChannelHandlerContext ctx, Channel channel,
16. ChannelBuffer buffer) throws Exception {
17.
18. ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
19. if (frame == null) {
20. return null;
21. }
22.
23. byte[] bytes = new byte[frame.readInt()];
24. frame.readBytes(bytes);
25.
26. String content = new String(bytes);
27. return content;
28. }
29.
30. @Override
31. protected Object decodeLast(ChannelHandlerContext ctx, Channel channel,
32. ChannelBuffer buffer) throws Exception {
33.
34. return this.decode(ctx, channel, buffer);
35. }
36.
37.}
1./**
2. * 消息编码器
3. *
4. */
5.public class MessageEncoder extends LengthFieldPrepender {
6.
7. public MessageEncoder(int lengthFieldLength) {
8. super(lengthFieldLength);
9. }
10.
11. @Override
12. protected Object encode(ChannelHandlerContext ctx, Channel channel,
13. Object obj) throws Exception {
14.
15. ChannelBuffer ob = ChannelBuffers.dynamicBuffer(channel.getConfig().getBufferFactory());
16.
17. String message = (String)obj;
18.
19. byte[] strBytes = message.getBytes();
20. ob.writeInt(strBytes.length);
21. ob.writeBytes(strBytes);
22.
23. return super.encode(ctx, channel, ob);
24. }
25.
26.}
01.bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
02. public ChannelPipeline getPipeline() throws Exception {
03. ChannelPipeline pipeline = new DefaultChannelPipeline();
04. pipeline.addLast("decoder", new MessageDecoder(Integer.Max_Value,0,4,0,4));
pipeline.addLast("encoder", new MessageEncoder(4));
05. pipeline.addLast("handler", new Handler);
06. return pipeline;
07. }
08. });
我原来是这样的(下面是手打的,可能有出入),运行正常的:
01.bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
02. public ChannelPipeline getPipeline() throws Exception {
03. ChannelPipeline pipeline = new DefaultChannelPipeline();
04. pipeline.addLast("decoder", new StringDecoder));
pipeline.addLast("encoder", new StringEncoder);
05. pipeline.addLast("handler", new Handler);
06. return pipeline;
07. }
08. });
但是长字符串不行了,后来网上查了,就改成上面的,但是出错,求高手出现