原生BIO Socket怎么接收Netty服务端发送的数据
netty服务端是echo的形式,和BIO的Socket客户端(项目要求)进行测试,发现只能Client向服务端发,服务端发出的东西,客户端接收不到。
我发现,如果把Encoder,Decoder,之类的全部注释掉,然后只留下ServerHandler,好像可以返回数据,但是单纯返回数据不是我想要的,我要自己构造数据发给非Netty的client,应该怎么做?
public class Server {
//端口定义
private int port;
//Event池 管理易阻塞逻辑事务
static final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
public Server(int port) {
this.port = port;
}
public void run() throws Exception {
//boss池 管理连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//worker池 管理io流
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("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
ch.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
ch.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
ch.pipeline().addLast(new ServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 绑定端口,开始接收进来的连接
ChannelFuture f = b.bind(port).sync();
System.out.println("Server start listen at " + port );
// 等待服务器 socket 关闭 。
// 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new Server(port).run();
}
}
----------------------------------------------
public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println(ctx.channel().remoteAddress()+"->Server :"+ msg.toString());
ctx.write(msg); // (1)
ctx.flush(); // (2)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
----------------------------
client端io流
-----------------------------
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
pw.println("123123");
InputStreamReader isr=new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(isr);
String response=br.readLine();
System.out.println("客户端收到"+response);