netty简单聊天程序之单聊

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

代码示例

  1. 根据netty的websoctet实现单聊
这里在传输的数据格式用文本转JSON的

@Override
	protected void channelRead0(ChannelHandlerContext ctx,
		  TextWebSocketFrame msg) throws Exception { // (1)
		  ObjectMapper mapper = new ObjectMapper();
		  Message message = mapper.readValue(msg.text(), Message.class);
		  
		  Channel incoming = ctx.channel();
		  if(null!=message) {
			  if(ChatType.BIND.equals(message.getCmd())){//绑定上线
				  ChannelManager.addChannel(message.getFrom(), incoming);
			  }else if(ChatType.LEAVE.equals(message.getCmd())) {
				  ChannelManager.removeChannelByCode(message.getFrom());
			  }else if(ChatType.SINGLE.equals(message.getCmd())) {
				  message.setMsg(HtmlUtils.htmlEscape(message.getMsg()));
				  if(null!=ChannelManager.getChannel(message.getAccept())) {
				    ChannelManager.getChannel(message.getAccept()).writeAndFlush(new TextWebSocketFrame(mapper.writeValueAsString(message))); 
				  }else {
					 String from=message.getFrom();
					 message.setFrom(message.getAccept());
					 message.setAccept(from);
					 message.setMsg("["+message.getFrom()+"]未上线");
					 incoming.writeAndFlush(new TextWebSocketFrame(mapper.writeValueAsString(message)));
				  }
			  }else if(ChatType.GROUP.equals(message.getCmd())) {
				  message.setMsg(HtmlUtils.htmlEscape(message.getMsg()));
			  }else {
				  System.out.println("未识别的命令");
			  }
		  }
	}
  1. 简单的数据格式
    private String cmd;//1.绑定上线 2.下线 3.单聊 4.群聊
	private String from;//用户ID
	private String accept;//接受ID
	private String group;//组ID
	private String msg;//文本信息
  1. 效果

netty简单聊天程序之单聊_第1张图片

netty简单聊天程序之单聊_第2张图片

转载于:https://my.oschina.net/findurl/blog/2396989

你可能感兴趣的:(netty简单聊天程序之单聊)