代码之家  ›  专栏  ›  技术社区  ›  Alex x

java netty作为tcpServer,delphi TIdTCPClient作为tcpClient

  •  0
  • Alex x  · 技术社区  · 7 年前

    public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new TcpServerHandler());
                        }
                    });
            ChannelFuture f = b.bind(8080).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
    
    
    public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
        try {
            ByteBuf in = (ByteBuf) msg;
            System.out.println("channelRead:" + in.toString(CharsetUtil.UTF_8));
            byte[] responseByteArray = "hello".getBytes("UTF-8");
            ByteBuf out = ctx.alloc().buffer(responseByteArray.length);
            out.writeBytes(responseByteArray);
            ctx.writeAndFlush(out);
            //ctx.write("hello");
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws  UnsupportedEncodingException{
        System.out.println("channelActive:" + ctx.channel().remoteAddress());
        ChannelGroups.add(ctx.channel());
    
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("channelInactive:" + ctx.channel().remoteAddress());
        ChannelGroups.discard(ctx.channel());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
    

    }

      AStream := TStringStream.Create;
      IdTCPClient.IOHandler.ReadStream(AStream);
    

    我还使用

    IdTCPClient.IOHandler.ReadLn()
    

    并且仍然无法获取返回数据。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Remy Lebeau    7 年前

    您的Delphi代码与Java代码不匹配,这就是您的客户端无法工作的原因。

    的默认参数 TIdIOHandler.ReadStream() 根据数据流的值,使用网络字节顺序(大端)的32位或64位整数,以字节为单位,期望流数据以流长度为前导 TIdIOHandler.LargeStream

    的默认参数 TIdIOHandler.ReadLn() CRLF 或裸露- LN 终结者。Java代码没有在数组字节的末尾发送任何行终止符。

    AReadUntilDisconnect 参数 TIdIOHandler.ReadStream() 为true,或使用 TIdIOHandler.AllData()

    TCP是面向流的,而不是面向消息的。发送方必须明确消息的结束位置和下一条消息的开始位置。