SimpleChannelHandler建立文本级的通讯

本文介绍了一个使用Netty实现的简单文本通信服务器示例。该服务器通过文本级通信简化调试流程,采用ServerHandler处理连接与消息事件。文章展示了如何配置ServerBootstrap及设置管道处理器,包括帧解码器和字符串编解码器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初学者用netty比较适合用文本级通讯,这样纠错简单,调试速度快。


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是视为未结束的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值