初学者用netty比较适合用文本级通讯,这样纠错简单,调试速度快。
继承自SimpleChannelHandler ,这个起步比较容易。
channelConnected来个连续问候,并不是必须的。
handleUpstream和handleDownstream目前只是记录一下变化,可以更好地看清楚具体的细节,并不做实际事。
messageReceived是接收信息处理后返回的主函数,现在只是加了echo再返回。
再加一个启动server就行了。注意pipeline里加的东西,frameDecoder是换行符处理,以行为单位进行处理的。stringDecoder和stringEncoder都是将传输内容视为字符串来处理的。
bootstrap.bind就是用来监听端口的。
要注意client发送的时候要加上\n,因为服务端加了frameDecoder以换行符为结束,所以不加\n是视为未结束的。
public class ServerHandler extends SimpleChannelHandler {
继承自SimpleChannelHandler ,这个起步比较容易。
public void channelConnected(
ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
// Send greeting for a new connection.
e.getChannel().write("welcome\n");
}
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
// Log all channel state changes.
if (e instanceof ChannelStateEvent) {
logger.debug("Channel state changed: " + e);
}
super.handleUpstream(ctx, e);
}
public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
// Log all channel state changes.
if (e instanceof MessageEvent) {
logger.debug("Writing:: " + e);
}
super.handleDownstream(ctx, e);
}
channelConnected来个连续问候,并不是必须的。
handleUpstream和handleDownstream目前只是记录一下变化,可以更好地看清楚具体的细节,并不做实际事。
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
// Send back the received message to the remote peer.
Object msg = e.getMessage();
logger.debug("e.getMessage():"+msg+" class:"+msg.getClass());
e.getChannel().write("echo:"+msg);
e.getChannel().close();
}
messageReceived是接收信息处理后返回的主函数,现在只是加了echo再返回。
public class Server {
private static final int SERVER_PORT = 10000;
public static void main(String[] args) throws Exception {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Set up the default event pipeline.
ServerHandler handler = new ServerHandler();
ChannelPipeline pipeline = bootstrap.getPipeline();
pipeline.addLast("frameDecoder", new DelimiterBasedFrameDecoder(8192,Delimiters.lineDelimiter()));
pipeline.addLast("stringDecoder", new StringDecoder("UTF-8"));
pipeline.addLast("stringEncoder", new StringEncoder("UTF-8"));
pipeline.addLast("handler", handler);
// Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(SERVER_PORT));
}
}
再加一个启动server就行了。注意pipeline里加的东西,frameDecoder是换行符处理,以行为单位进行处理的。stringDecoder和stringEncoder都是将传输内容视为字符串来处理的。
bootstrap.bind就是用来监听端口的。
要注意client发送的时候要加上\n,因为服务端加了frameDecoder以换行符为结束,所以不加\n是视为未结束的。