
聊天室入门 1.html+Netty 2.websocket
发布日期:2021-05-04 15:46:24
浏览次数:26
分类:精选文章
本文共 4825 字,大约阅读时间需要 16 分钟。
1)服务端
ChatServer.java
package chat;import chat.handler.WSServerInitializer;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;public class ChatServer { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WSServerInitializer()); int port = 8088; ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); System.out.println("聊天服务器启动成功 port:" + port); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }}
2)WSServerInitializer.java
package chat.handler;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.http.HttpObjectAggregator;import io.netty.handler.codec.http.HttpServerCodec;import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;import io.netty.handler.stream.ChunkedWriteHandler;public class WSServerInitializer extends ChannelInitializer{ protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(1024 * 64)); pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); // 业务Handler pipeline.addLast(new ChatHandler()); }}
3)ChatHandler.java
package chat.handler;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;import java.time.LocalDateTime;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;public class ChatHandler extends SimpleChannelInboundHandler{ // 存储所有的客户端 private static ConcurrentHashMap clientHashMap = new ConcurrentHashMap<>(); protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception { String content = textWebSocketFrame.text(); for (ChannelHandlerContext key : clientHashMap.keySet()) { ChannelHandlerContext ctx = key; ctx.channel().writeAndFlush(new TextWebSocketFrame(LocalDateTime.now() + " " + channelHandlerContext.channel().remoteAddress() + "说: " + content)); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("客户端进来了:" + ctx.channel().remoteAddress()); clientHashMap.put(ctx, ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("客户端断开连接:" + ctx.channel().remoteAddress()); clientHashMap.remove(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("客户端异常:" + ctx.channel().remoteAddress()); cause.printStackTrace(); ctx.close(); }}
pom.xml
4.0.0 org.example NettyChatRoom 1.0 org.apache.maven.plugins maven-compiler-plugin 8 8 maven-assembly-plugin 3.3.0 chat.ChatServer jar-with-dependencies false make-assembly package single io.netty netty-all 4.1.32.Final
2)客户端
ChatClient.html
发送消息:接受消息:
发表评论
最新留言
关注你微信了!
[***.104.42.241]2025年04月14日 03时03分42秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
小程序之wx:request(转)
2021-05-10
解决数据库报ORA-02289:序列不存在错误
2021-05-10
map[]和map.at()取值之间的区别
2021-05-11
成功解决升级virtualenv报错问题
2021-05-11
【SQLI-Lab】靶场搭建
2021-05-11
Xception 设计进化
2021-05-11
【Bootstrap5】精细学习记录
2021-05-11
Hololens2开发笔记-捕获照片到内存并上传至服务器(unity)
2021-05-11
SkyWalking性能剖析
2021-05-11
LeetCode197.打家劫舍
2021-05-11
A simple problem HDU-2522 【数学技巧】
2021-05-11
487-3279 POJ-1022【前导0~思维漏洞】
2021-05-11
Struts2-从值栈获取list集合数据(三种方式)
2021-05-11
Linux之磁盘管理
2021-05-11
vscode中快速生成vue模板
2021-05-11
ERP项目成功的关键因素:团队建设
2021-05-11