JAVA Netty框架下的聊天程序(Maven项目)

sever handler

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; 
import java.net.InetSocketAddress;
//import java.nio.channels.Channel;细心看看import的是什么玩意儿。。。!!!
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.channel.SimpleChannelInboundHandler;
@Sharable
public class handler_1_0_0 extends SimpleChannelInboundHandler<String> {
	 public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	//ChannelHandlerContext:代表了ChannelHandler和ChannelPipeline之间的关联
	 //handlerAdded在ChannelHandler添加到ChannelPipeline中时被调用
	 @Override
	    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel incomming = ctx.channel();//返回绑定到这个实例的Channel
		for(Channel channel:channels){
            channel.writeAndFlush("System:"+incomming.remoteAddress()+"comes");            
        }
		 channels.add(ctx.channel());
	 }
	 @Override
	    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
	        Channel incomming = ctx.channel();
	        //将收到的信息转发给全部的客户端channel
	        for(Channel channel:channels){
	            if(channel != incomming) {
	                channel.writeAndFlush( incomming.remoteAddress() + ":" + msg + "\n");
	            }else{
	                channel.writeAndFlush("U:"+msg+"\n");
	            }
	        }
	    }
	 @Override
	    public void channelActive(ChannelHandlerContext ctx) throws Exception {
	        //服务端接收到客户端上线通知
	        Channel incoming = ctx.channel();
	        System.out.println("System:" + incoming.remoteAddress()+" in");
	    }
	 @Override
	    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	        Channel incoming = ctx.channel();
	        System.out.println("System:" + incoming.remoteAddress()+"with some bugs and errors");
	        cause.printStackTrace();
	        ctx.close();
	    }
	 }

sever主程序

import io.netty.bootstrap.ServerBootstrap;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; 
import java.net.InetSocketAddress;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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 sever1_0_0 {
       private final int port;
       public sever1_0_0(int port) {
    	   this.port = port;
       }
       public static void main(String[] Zing) throws Exception{
    	   //选择的端口是8739
    	    new sever1_0_0(8739).start();//main函数可以在类中实例化该类。。。
       }
       public void start() throws Exception{
    	   EventLoopGroup parentGroup = new NioEventLoopGroup();
           EventLoopGroup childGroup = new NioEventLoopGroup();
           ServerBootstrap b = new ServerBootstrap();
           try {
        	   b.group(parentGroup, childGroup)
               .channel(NioServerSocketChannel.class)
               .childHandler(new ChannelInitializer<SocketChannel>() {
            	   @Override
            	public void initChannel(SocketChannel ch) throws Exception{
            		//addLast后面括号中的字符串是个代号
            		ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    ch.pipeline().addLast("decoder", new StringDecoder());
                    ch.pipeline().addLast("encoder", new StringEncoder());
                    ch.pipeline().addLast("handler", new handler_1_0_0());
            
            	}
               })
               .option(ChannelOption.SO_BACKLOG, 128)//TCP协议设置参数
               .childOption(ChannelOption.SO_KEEPALIVE, true);//TCP协议设置参数
        	   System.out.println("sever initialized .");
        	   ChannelFuture f = b.bind(port).sync();//异步地绑定服务器,调用sync()阻塞,直到绑定完成
        	   f.channel().closeFuture().sync();//阻塞当前线程,直到完成
        	   
           }finally {
        	   parentGroup.shutdownGracefully().sync();//关闭EventLoop并释放所有资源
               childGroup.shutdownGracefully().sync();
        	   System.out.println("sever closed .");
           }
       }
       

}

sever的xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>ZinggroupId>
  <artifactId>ZingartifactId>
  <version>0.0.1-SNAPSHOTversion>


 <properties>
         <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
     properties>

  <dependencies>
  	<dependency>
	    <groupId>io.nettygroupId>
	    <artifactId>netty-allartifactId> 
	    <version>4.1.33.Finalversion>
	dependency>
  dependencies>
project>

clienthandler

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class client_handler extends SimpleChannelInboundHandler<String>{
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
    }
	//@Override
}

client主程序

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;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import io.netty.bootstrap.ServerBootstrap;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel; 
import java.net.InetSocketAddress;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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 client {
    private final int port;
    private final String host;//java socket(String host, int port)

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

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

        try{
            //是一个启动NIO服务的辅助启动类
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                    	@Override
                    	public void initChannel(SocketChannel ch) throws Exception{
                    		ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                            ch.pipeline().addLast("decoder", new StringDecoder());
                            ch.pipeline().addLast("encoder", new StringEncoder());
                            ch.pipeline().addLast("handler", new client_handler());
                    	}
                    });            
            Channel channel = b.connect(host, port).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true){
                channel.writeAndFlush(in.readLine()+"\r\n");
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally{
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new client("127.0.0.1",8739).run();
    }

}

client的xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>ZinggroupId>
  <artifactId>Zing01artifactId>
  <version>0.0.1-SNAPSHOTversion>

  
  
  
   <properties>
         <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
     properties>

  <dependencies>
  	<dependency>
	    <groupId>io.nettygroupId>
	    <artifactId>netty-allartifactId> 
	    <version>4.1.33.Finalversion>
	dependency>
  dependencies>
project>

你可能感兴趣的:(JAVA Netty框架下的聊天程序(Maven项目))