聊天室入门 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

    
发送消息:
接受消息:

 

 

 

 

 

 

 

 

 

 

上一篇:反射调用方法的例子: 加法
下一篇:mac下jdk1.8安装后的目录

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月14日 03时03分42秒