Netty集成WebSocket实现客户端、服务端长连接
生活随笔
收集整理的這篇文章主要介紹了
Netty集成WebSocket实现客户端、服务端长连接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 概述
(1) Http協議是無狀態的,瀏覽器和服務器間的請求響應一次,下ー次會重新創建連接。
(2) 要求:實現基于 websockete的長連接的全雙工的交互。
(3) 改變Http協議多次請求的約束,實現長連接了,服務器可以發送消息給瀏覽器。
(4) 客戶端瀏覽器和服務器端會相互感知,比如服務器關閉了,瀏覽器會感知,同樣瀏覽器關閉了,服務器會感知。
2 實現
2.1 WebSocketServerConsts
public final class WebSocketServerConsts {private WebSocketServerConsts() {}public static final Integer port = 8888;}2.2 WebSocketHandler
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {System.out.println("服務器接收到消息:" + msg.text());//回復消息ctx.channel().writeAndFlush(new TextWebSocketFrame("服務器時間" + LocalDateTime.now() + " " + msg.text()));}/*** 客戶端連接后*/@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {System.out.println("handlerAdded 被調用" + ctx.channel().id().asLongText());System.out.println("handlerAdded 被調用" + ctx.channel().id().asShortText());}/***客戶端斷開連接時觸發*/@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {System.out.println("handlerRemoved 被調用" + ctx.channel().id().asLongText());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("發生異常" + cause.getMessage());ctx.channel();} }2.3 WebSocketServerChannelInitializer
public class WebSocketServerChannelInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//http 編碼、解碼器pipeline.addLast(new HttpServerCodec());//以塊的方式寫pipeline.addLast(new ChunkedWriteHandler());//http數據在傳輸過程中是分段的,HttpObjectAggregator可以將多個段聚合pipeline.addLast(new HttpObjectAggregator(8192));//websocketServerProtocolHandler,將http協議升級為ws協議,瀏覽器請求時uri為 ws://localhost:8888/hellopipeline.addLast(new WebSocketServerProtocolHandler("/hello"));//自定義handlerpipeline.addLast(new WebSocketHandler());} }2.4 WebSocketServer
public class WebSocketServer {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 WebSocketServerChannelInitializer());ChannelFuture channelFuture = serverBootstrap.bind(WebSocketServerConsts.port).sync();System.out.println("服務器已經開啟......");channelFuture.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}2.5 hello.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>WebSocket</title> </head> <body><form onsubmit="return false"><textarea name="message" style="height: 300px;width: 300px;"></textarea><input type="button" value="發送消息" onclick="send(this.form.message.value)"><textarea id="responseText" name="responseText" style="height: 300px;width: 300px;"></textarea><input type="button" value="清空內容" onclick="document.getElementById('responseText').value=''"></form><script>var socket;if (window.WebSocket) {socket = new WebSocket("ws://localhost:8888/hello");//接收服務器消息socket.onmessage = function (ev) {var rt = document.getElementById("responseText");rt.value = rt.value + "\n" + ev.data;}//連接開啟socket.onopen = function (ev) {var rt = document.getElementById("responseText");rt.value = "連接開啟......";}//連接關閉socket.onclose = function (ev) {var rt = document.getElementById("responseText");rt.value = rt.value + "\n" + "連接關閉了......";}} else {alert("當前瀏覽器不支持websocket");}//發送消息function send(message) {if (!window.WebSocket) {return;}if (socket.readyState == WebSocket.OPEN) {socket.send(message);} else {alert("連接沒有開啟");}}</script></body> </html>3 測試
關閉瀏覽器后:
總結
以上是生活随笔為你收集整理的Netty集成WebSocket实现客户端、服务端长连接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Arduino(MEGA2560)最小系
- 下一篇: 5.4.3控制器设计 微程序控制器 微指