赞
踩
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议。它允许服务端主动向客户端推送数据,从而实现了实时通信。WebSocket 建立在 HTTP 之上,但与 HTTP 的轮询(Polling)和长轮询(Long Polling)相比,WebSocket 只需一次握手,即可在客户端和服务器之间建立持久的连接,并通过这个连接进行双向数据传输。
Netty 是一个高性能、异步事件驱动的网络应用程序框架,支持快速开发可维护的高性能协议服务器和客户端。它基于 Java NIO(非阻塞 I/O)进行封装,提供了更简单易用的 API,并解决了 NIO 编程中常见的复杂性和错误。
Netty WebSocket 的应用场景非常广泛,主要集中在需要实时、双向通信的 web 应用中。以下是一些典型的应用场景:
在Netty中实现WebSocket的Demo可以分为服务端和客户端两部分。以下是一个简化的Netty WebSocket Demo示例,展示了如何搭建一个基本的WebSocket服务器和客户端。
确保你已经将Netty的依赖项添加到你的项目中。如果你使用Maven,可以在pom.xml文件中添加以下依赖:
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.x</version> <!-- 使用你需要的Netty版本 -->
</dependency>
</dependencies>
WebSocket服务器的代码
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.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; public class WebSocketServer { private int port; public WebSocketServer(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) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // HTTP编解码器 pipeline.addLast(new HttpServerCodec()); // 聚合HTTP消息 pipeline.addLast(new HttpObjectAggregator(65536)); // 支持大消息的写操作 pipeline.addLast(new ChunkedWriteHandler()); // WebSocket协议处理 pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); // 指定WebSocket的路径为"/ws" // 自定义的WebSocket业务处理 pipeline.addLast(new WebSocketServerHandler()); } }); // 开始监听端口 ChannelFuture f = b.bind(port).sync(); // 等待服务器套接字关闭 f.channel().closeFuture().sync(); } finally { // 关闭所有的事件循环以终止所有的线程 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 8080; } new WebSocketServer(port).run(); } private static class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { // 打印接收到的消息 System.out.println("Received message: " + msg.text()); // 回显消息 ctx.channel().writeAndFlush(new TextWebSocketFrame("Echo: " + msg.text())); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // 当handler被添加到ChannelPipeline时调用 System.out.println("WebSocket client connected: " + ctx.channel().remoteAddress()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // 当handler从ChannelPipeline中移除时调用 System.out.println("WebSocket client disconnected: " + ctx.channel().remoteAddress()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 当异常被抛出时调用 cause.printStackTrace(); ctx.close(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。