可以使用write:1,实现想服务端存储1的数据,使用read命令可以读取刚才的写入的数据,效果如下
有可能会报错is not a @Sharable handler, so can’t be added or removed multiple times.
服务端
read
read is inputs
请输入消息:
客户端读取服务返回的数据:1
客户端读取服务返回的数据:服务端已经读取消息完成!read
write:999
write:999 is inputs
请输入消息:
客户端读取服务返回的数据:服务端已经读取消息完成!write:999
read
read is inputs
请输入消息:
客户端读取服务返回的数据:999
客户端读取服务返回的数据:服务端已经读取消息完成!read
package sample.netty.newtest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class nettyServerTest {
private int port;
public nettyServerTest(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new NettyServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public class NettyServerHandler extends ChannelInboundHandlerAdapter { // (1)
int currentValue=0;
String pubMSG;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException { // (2)
String byteBuf = (String) msg;
pubMSG=byteBuf;
System.out.println("客户端发来的消息是:" + byteBuf);
if(byteBuf.contains("write:")){
currentValue=Integer.parseInt(byteBuf.split(":")[1]);
}
if(byteBuf.contains("read")){
ctx.writeAndFlush(Unpooled.copiedBuffer(currentValue+"\r\n", CharsetUtil.UTF_8));
}
}
//数据读取完毕事件
public void channelReadComplete(ChannelHandlerContext ctx) throws IOException, InterruptedException {
//数据读取完毕,将信息包装成一个Buffer传递给下一个Handler,Unpooled.copiedBuffer会返回一个Buffer
//调用的是事件处理器的上下文对象的writeAndFlush方法
//意思就是说将 你好 传递给了下一个handler
ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已经读取消息完成!"+pubMSG+"\r\n", CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
public static void main(String[] args) throws Exception {
int port = 1003;
// if (args.length > 0) {
// port = Integer.parseInt(args[0]);
// }
new nettyServerTest(port).run();
}
}
客户端
package sample.netty.newtest;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.util.Scanner;
public class nettyClient {
ChannelHandlerContext ctxOut;
public static void main(String[] args) throws Exception {
NettyClientHandlerInner nettyClientHandlerInner=new NettyClientHandlerInner();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
Scanner scanner=new Scanner(System.in);
System.out.println("请输入消息:");
String inputs=scanner.nextLine();
System.out.println(inputs+" is inputs");
nettyClientHandlerInner.sendMSG(inputs);
}
}
}).start();
connectToServer(nettyClientHandlerInner);
System.out.println(222222);
// while (true){
// Scanner scanner=new Scanner(System.in);
// String inputs=scanner.nextLine();
// nettyClientHandlerInner.ctxOut.writeAndFlush(Unpooled.copiedBuffer(inputs+“\r\n”, CharsetUtil.UTF_8));;
// }
}
public static void connectToServer(NettyClientHandlerInner nettyClientHandler){
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(nettyClientHandler);
}
});
// Start the client.
ChannelFuture f = b.connect("127.0.0.1", 1003).sync(); // (5)
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
}
//客户端业务处理类
class NettyClientHandlerInner extends ChannelInboundHandlerAdapter {
ChannelHandlerContext ctxOut;
//通道就绪事件(就是在bootstrap启动助手配置中addlast了handler之后就会触发此事件)
//但我觉得也可能是当有客户端连接上后才为一次通道就绪
public void channelActive(ChannelHandlerContext ctx) throws IOException, InterruptedException {
System.out.println(“客户端消息,通道激活,可以发送消息了”);
ctxOut=ctx;
}
//数据读取事件
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//传来的消息包装成字节缓冲区
String byteBuf = (String) msg;
// ByteBuf byteBuf = (ByteBuf) msg;
//Netty提供了字节缓冲区的toString方法,并且可以设置参数为编码格式:CharsetUtil.UTF_8
System.out.println(“客户端读取服务返回的数据:” + byteBuf);
}
public void sendMSG(String msg){
ctxOut.writeAndFlush(Unpooled.copiedBuffer(msg+"\r\n", CharsetUtil.UTF_8));
}
}
主要是在服务端的handler上加了注解 @ChannelHandler.Sharable
同时在channel.pipeline().addLast(new NettyServerHandler());
package sample.appfunction.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import java.io.IOException;
public class nettyServerQA {
public int currentValue=0;
public String pubMSG;
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new NettyServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(1003).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException { // (2)
String byteBuf = (String) msg;
pubMSG=byteBuf;
// System.out.println("客户端发来的消息是:" + byteBuf);
System.out.println("收到连接的原信息 "+pubMSG);
if(byteBuf.contains("write:")){
currentValue=Integer.parseInt(byteBuf.split(":")[1]);
System.out.println("收到写入请求 "+currentValue);
}
if(byteBuf.contains("read")){
ctx.writeAndFlush(Unpooled.copiedBuffer(currentValue+"\r\n", CharsetUtil.UTF_8));
System.out.println("收到读取请求 "+currentValue);
}
}
//数据读取完毕事件
public void channelReadComplete(ChannelHandlerContext ctx) throws IOException, InterruptedException {
//数据读取完毕,将信息包装成一个Buffer传递给下一个Handler,Unpooled.copiedBuffer会返回一个Buffer
//调用的是事件处理器的上下文对象的writeAndFlush方法
//意思就是说将 你好 传递给了下一个handler
// ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已经读取消息完成!"+pubMSG+"\r\n", CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
Channel channel = ctx.channel();
if(channel.isActive())ctx.close();
}
}
public static void main(String[] args) {
try {
new nettyServerQA().run();
} catch (Exception e) {
e.printStackTrace();
System.out.println("server netty exception");
}
}
}