123456789101112131415161718192021222324252627282930313233343536 |
- package cn.com.zyjblogs.chat.netty;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
- import io.netty.util.CharsetUtil;
- import java.util.UUID;
- public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
- private int count=0;
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- ctx.close();
- }
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
- //接收数据,并处理
- System.out.println("服务端接收信息:");
- System.out.println("长度="+msg.getLen());
- System.out.println("内容="+new String(msg.getContent(),CharsetUtil.UTF_8));
- System.out.println("服务器接收消息包数量="+(++this.count));
- //回复消息
- String responseContent = UUID.randomUUID().toString();
- int responseLen = responseContent.getBytes(CharsetUtil.UTF_8).length;
- MessageProtocol messageProtocol = new MessageProtocol();
- messageProtocol.setLen(responseLen);
- messageProtocol.setContent(responseContent.getBytes(CharsetUtil.UTF_8));
- ctx.writeAndFlush(messageProtocol);
- }
- }
|