我编了一个java程序,功能是实现netty的服务端,开启9400端口接收数据。
public class echoServer {
private int port;
public echoServer(int port) { this.port = port; }
public void start() {
EventLoopGroup boosGroup = new NioEventLoopGroup(1); //bossGroup
EventLoopGroup workerGroup = new NioEventLoopGroup(); //workGroup
try{ServerBootstrap sbs = new ServerBootstrap().group(boosGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast("decoder", new StringDecoder());
ch.pipeline().addLast("encoder", new StringEncoder());
ch.pipeline().addLast(new echoServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = sbs.bind(port).sync();
System.out.println("Server start listen at " + port);
future.channel().closeFuture().sync();
} catch (Exception e) {
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new echoServer(9400).start();
}
}
客户端使用的软件为Insomnia,向9400端口发送一个消息。
想尝试将服务端接收到的消息原样返回给Insomnia。
public class echoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server channelRead....");
System.out.println(ctx.channel().remoteAddress()+"->Server :"+msg.toString());
ctx.write("Server write"+msg); //原样返回
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
但却失败了
想问一问具体原因是什么?
以及请问如何解决?