MyServerHandler.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package cn.com.zyjblogs.chat.netty;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.SimpleChannelInboundHandler;
  4. import io.netty.util.CharsetUtil;
  5. import java.util.UUID;
  6. public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
  7. private int count=0;
  8. @Override
  9. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  10. ctx.close();
  11. }
  12. @Override
  13. protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
  14. //接收数据,并处理
  15. System.out.println("服务端接收信息:");
  16. System.out.println("长度="+msg.getLen());
  17. System.out.println("内容="+new String(msg.getContent(),CharsetUtil.UTF_8));
  18. System.out.println("服务器接收消息包数量="+(++this.count));
  19. //回复消息
  20. String responseContent = UUID.randomUUID().toString();
  21. int responseLen = responseContent.getBytes(CharsetUtil.UTF_8).length;
  22. MessageProtocol messageProtocol = new MessageProtocol();
  23. messageProtocol.setLen(responseLen);
  24. messageProtocol.setContent(responseContent.getBytes(CharsetUtil.UTF_8));
  25. ctx.writeAndFlush(messageProtocol);
  26. }
  27. }