Netty网络聊天室完整代码实现
生活随笔
收集整理的這篇文章主要介紹了
Netty网络聊天室完整代码实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Netty服務端:
package cn.zhangxueliang.netty.chat;import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; 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 ChatServer {private 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).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) {ChannelPipeline pipeline=ch.pipeline();//往pipeline鏈中添加一個解碼器pipeline.addLast("decoder",new StringDecoder());//往pipeline鏈中添加一個編碼器pipeline.addLast("encoder",new StringEncoder());//往pipeline鏈中添加自定義的handler(業務處理類)pipeline.addLast(new ChatServerHandler());}});System.out.println("Netty Chat Server啟動......");ChannelFuture f = b.bind(port).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();System.out.println("Netty Chat Server關閉......");}}public static void main(String[] args) throws Exception {new ChatServer(9999).run();} }Netty服務端自定義handler:
package cn.zhangxueliang.netty.chat;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.GlobalEventExecutor;import java.util.ArrayList; import java.util.List;//自定義一個服務器端業務處理類 public class ChatServerHandler extends SimpleChannelInboundHandler<String> {public static List<Channel> channels = new ArrayList<>();@Override //通道就緒public void channelActive(ChannelHandlerContext ctx) {Channel inChannel=ctx.channel();channels.add(inChannel);System.out.println("[Server]:"+inChannel.remoteAddress().toString().substring(1)+"上線");}@Override //通道未就緒public void channelInactive(ChannelHandlerContext ctx) {Channel inChannel=ctx.channel();channels.remove(inChannel);System.out.println("[Server]:"+inChannel.remoteAddress().toString().substring(1)+"離線");}@Override //讀取數據protected void channelRead0(ChannelHandlerContext ctx, String s) {Channel inChannel=ctx.channel();for(Channel channel:channels){if(channel!=inChannel){channel.writeAndFlush("["+inChannel.remoteAddress().toString().substring(1)+"]"+"說:"+s+"\n");}}}}Netty客戶端:
package cn.zhangxueliang.netty.chat;import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; 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 java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner;//聊天程序客戶端 public class ChatClient {private final String host; //服務器端IP地址private final int port; //服務器端端口號public ChatClient(String host, int port) {this.host = host;this.port = port;}public void run(){EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch){ChannelPipeline pipeline=ch.pipeline();//往pipeline鏈中添加一個解碼器pipeline.addLast("decoder",new StringDecoder());//往pipeline鏈中添加一個編碼器pipeline.addLast("encoder",new StringEncoder());//往pipeline鏈中添加自定義的handler(業務處理類)pipeline.addLast(new ChatClientHandler());}});ChannelFuture cf=bootstrap.connect(host,port).sync();Channel channel=cf.channel();System.out.println("------"+channel.localAddress().toString().substring(1)+"------");Scanner scanner=new Scanner(System.in);while (scanner.hasNextLine()){String msg=scanner.nextLine();channel.writeAndFlush(msg+"\r\n");}} catch (Exception e) {e.printStackTrace();} finally {group.shutdownGracefully();}}public static void main(String[] args) throws Exception {new ChatClient("127.0.0.1",9999).run();} }Netty客戶端handler:
package cn.zhangxueliang.netty.chat;import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler;//自定義一個客戶端業務處理類 public class ChatClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {System.out.println(s.trim());} }?
總結
以上是生活随笔為你收集整理的Netty网络聊天室完整代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java经典逻辑编程题(不死神兔问题)
- 下一篇: Netty使用protobuf进行消息编