netty实战--开发一个简单的聊天功能

netty 版本:4.1.6

JDK版本:1.8.0_131


客户端:ChatClient

import java.io.BufferedReader;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ChatClient {

 private final int port;
 private final String host;

 public ChatClient(String host, int port) {
  this.host = host;
  this.port = port;

 }

 public void run() throws Exception {
  EventLoopGroup group = new NioEventLoopGroup();

  try {

   Bootstrap b = new Bootstrap();

   b.group(group).channel(NioSocketChannel.class).handler(new ChatChannelInitializer());

   Channel channel = b.connect(host, port).sync().channel();

   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

   while (true) {
    String msg = in.readLine();
    channel.writeAndFlush( msg+ "\r\n");
   }

  } finally {
   group.shutdownGracefully();
  }
 }

 public static void main(String[] args) throws Exception {
  new ChatClient("10.0.90.93",8080).run();
 }

客户端ChannelInitializer

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatChannelInitializer extends ChannelInitializer<Channel> {

 @Override
 protected void initChannel(Channel ch) throws Exception {

  ChannelPipeline p = ch.pipeline();
  
  p.addLast("framer",new DelimiterBasedFrameDecoder(1024,Delimiters.lineDelimiter()));
  p.addLast("StringDecoder",new StringDecoder());
  p.addLast("StringEncoder",new StringEncoder());
  
  p.addLast("handler",new ChatClientHander());
  
 }

}

客户端处理类:ChatClientHandler

package com.phei.netty.chat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ChatClientHander extends SimpleChannelInboundHandler<String> {

 @Override
 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

  System.out.println(msg);

 }

}

服务端:ChatServer

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ChatServer {

 private final int port;

 public ChatServer(int port) {
  this.port = port;

 }
 
 public void run() throws Exception
 {
  EventLoopGroup bossGroup = new NioEventLoopGroup();
  EventLoopGroup workerGroup = new NioEventLoopGroup();
  
  
  
  try {
   
   ServerBootstrap b = new ServerBootstrap();
   
   b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChatServerInitializer());
     
   b.bind(port).sync().channel().closeFuture().sync();
   
  } finally {

   bossGroup.shutdownGracefully();
   workerGroup.shutdownGracefully();
  }
 }

 public static void main(String[] args) throws Exception {
  new ChatServer(8080).run();
 }
}

服务端ChatServerInitializer:

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatServerInitializer extends ChannelInitializer<Channel> {

 @Override
 protected void initChannel(Channel ch) throws Exception {
  ChannelPipeline p = ch.pipeline();
  p.addLast("framer",new DelimiterBasedFrameDecoder(1024,Delimiters.lineDelimiter()));
  p.addLast("StringDecoder", new StringDecoder());
  p.addLast("StringEncoder", new StringEncoder());
  
  p.addLast("handler", new ChatServerHandler());
 }

}

服务端处理类:ChatServerHandler


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

 private final static ChannelGroup channels = new DefaultChannelGroup(new DefaultEventExecutorGroup(1).next());

 @Override
 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

  Channel incoming = ctx.channel();

  for (Channel ch : channels) {
   if (ch != incoming) {
    ch.writeAndFlush("[" + incoming.remoteAddress() + "] - " + msg + "\r\n");
   }
  }

 }

 @Override
 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
  
  
  Channel channel = ctx.channel();
  for(Channel ch :channels)
  {
   ch.writeAndFlush("[SERVER] - "+channel.remoteAddress() +" has joined.\r\n");
  }
  
  channels.add(channel);
  
 }

 @Override
 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  Channel channel = ctx.channel();
  for(Channel ch :channels)
  {
   ch.writeAndFlush("[SERVER] - "+channel.remoteAddress() +" has left.\r\n");
  }
  
  channels.remove(channel);
 }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值