【问题标题】:Netty Server throwing Exception when a simple Java Nio Client sends a message当一个简单的 Java Nio 客户端发送消息时,Netty 服务器抛出异常
【发布时间】:2017-10-28 02:04:06
【问题描述】:

我有一个使用 Netty 用 Ja​​va 设计的非常简单的服务器。我还使用 Java NIO 包编写了一个简单的客户端。我可以将 Netty 服务器与客户端连接,但是当消息发送到服务器时,我收到以下异常:

我的输出:

新客户端已连接:/127.0.0.1:1125 java.io.IOException: 远程主机在 sun.nio.ch.SocketDispatcher.read0(Native Method) 在 sun.nio.ch 上强行关闭了现有连接。 SocketDispatcher.read(SocketDispatcher.java:43) 在 sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) 在 sun.nio.ch.IOUtil.read(IOUtil.java:192) 在 sun.nio.ch io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100) 处 io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288) 处的 .SocketChannelImpl.read(SocketChannelImpl.java:380)。 channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123) at io.netty.channel.nio.NioEventLoop.processSelectedKey( NioEventLoop.java:644) 在 io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579) 在 io.netty.channel.nio.NioEventLoop.processSelectedKey s(NioEventLoop.java:496) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) at io。 netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138) at java.lang.Thread.run(Thread.java:745)

我的服务器程序:

public class EchoServer{

    private final int port;
    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception { 
            System.out.println("New client connected: " + ch.localAddress()); 

           ch.pipeline().addLast(newLengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4))            
      .addLast(new LengthFieldPrepender(4))
      .addLast(new EchoServerHandler());
    } 
      });
       ChannelFuture f = b.bind().sync();
       f.channel().closeFuture().sync();
       }
      finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main (String [] args) throws Exception {
        new EchoServer(1125).start();
    }
}

我的服务器处理程序:

public class EchoServerHandler extends ChannelInboundHandlerAdapter{

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
         ByteBuf in = (ByteBuf) msg;
         System.out.println(in.toString(CharsetUtil.UTF_8));        

    }

      @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

我的 NIO Java 客户端:

public class NIOJavaClient {

    public static void main(String[] args) throws IOException, InterruptedException {

        InetSocketAddress addr = new InetSocketAddress("localhost", 1125);
        SocketChannel client = SocketChannel.open(addr);

        System.out.println("Connecting to Server on port 1125...");

        int i=0;
         while(i<10){

            byte[] message = new String("Hi Server\n").getBytes();
            ByteBuffer buffer = ByteBuffer.wrap(message);
            client.write(buffer);
            buffer.clear();
                        i++;
    }
        client.close();
    }

}

现在我需要的东西是:

1) 我无法从客户端向服务器发送消息。目前我使用的是 Java NIO 客户端(不是 Netty)。将来我可能会以字节为单位从 C# 客户端向 netty 服务器发送消息。有可能吗?如果可以,该怎么做?

2) 我正在使用 LengthFieldBasedFrameDecoder 和 LengthPrepender 来消除半个字符串(从 NETTY 客户端发送的字符串每次都被切割成一个大小)。当我使用 Netty 客户端时,我成功接收到消息,但是当我使用在 Mina 或 C# 中设计的不同客户端时,我收到一个异常:超出长度帧。我怎样才能消除这种情况?

简而言之,我想连接一个以任何语言设计的客户端,它将字节发送到 Netty 服务器并消除半字符串。这对我来说是一个危急的情况。任何帮助都会非常显着。

【问题讨论】:

    标签: java c# sockets netty nio


    【解决方案1】:

    由于您在代码中使用LengthFieldBasedFrameDecoder,这意味着您需要以该处理程序接受的格式从简单程序发送数据包,即在网络顺序前面加上一个 4 字节值,给出长度即将到来的数据。

    NIO 客户端示例

    byte[] message = new String("Hi Server\n").getBytes();
    byte[] fullMessage = new byte[message.length + 4];
    fullMessage[0] = (byte)(message.length >> 24);
    fullMessage[1] = (byte)(message.length >> 16);
    fullMessage[2] = (byte)(message.length >> 8);
    fullMessage[3] = (byte)message.length;
    System.arraycopy(message, 0, messageFull, 4, message.length);
    ByteBuffer buffer = ByteBuffer.wrap(fullMessage);
    client.write(buffer);
    buffer.clear();
    

    似乎有更好的方法,因为您的协议工作以换行符结束(但这也可能是由于您尝试调试问题引起的),而不是在数据包前面加上长度,只需等待使用 DelimiterBasedFrameDecoder 处理程序的换行符,像这样使用它:

    ch.pipeline.addLast(new DelimiterBasedFrameDecoder(Delimiters.lineDelimiter()))
    // Don't forget to remove your old 2 handlers
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2014-11-01
      • 2012-08-07
      • 2011-07-04
      • 2012-12-05
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多