日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Netty网络聊天室完整代码实现

發(fā)布時間:2025/1/21 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Netty网络聊天室完整代码实现 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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(業(yè)務處理類)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;//自定義一個服務器端業(yè)務處理類 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 //讀取數(shù)據(jù)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(業(yè)務處理類)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;//自定義一個客戶端業(yè)務處理類 public class ChatClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {System.out.println(s.trim());} }

?

總結

以上是生活随笔為你收集整理的Netty网络聊天室完整代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。