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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Netty集成WebSocket实现客户端、服务端长连接

發(fā)布時(shí)間:2024/8/1 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Netty集成WebSocket实现客户端、服务端长连接 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1 概述

(1) Http協(xié)議是無狀態(tài)的,瀏覽器和服務(wù)器間的請(qǐng)求響應(yīng)一次,下ー次會(huì)重新創(chuàng)建連接。
(2) 要求:實(shí)現(xiàn)基于 websockete的長(zhǎng)連接的全雙工的交互。
(3) 改變Http協(xié)議多次請(qǐng)求的約束,實(shí)現(xiàn)長(zhǎng)連接了,服務(wù)器可以發(fā)送消息給瀏覽器。
(4) 客戶端瀏覽器和服務(wù)器端會(huì)相互感知,比如服務(wù)器關(guān)閉了,瀏覽器會(huì)感知,同樣瀏覽器關(guān)閉了,服務(wù)器會(huì)感知。

2 實(shí)現(xiàn)

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("服務(wù)器接收到消息:" + msg.text());//回復(fù)消息ctx.channel().writeAndFlush(new TextWebSocketFrame("服務(wù)器時(shí)間" + LocalDateTime.now() + " " + msg.text()));}/*** 客戶端連接后*/@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {System.out.println("handlerAdded 被調(diào)用" + ctx.channel().id().asLongText());System.out.println("handlerAdded 被調(diào)用" + ctx.channel().id().asShortText());}/***客戶端斷開連接時(shí)觸發(fā)*/@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {System.out.println("handlerRemoved 被調(diào)用" + ctx.channel().id().asLongText());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("發(fā)生異常" + 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數(shù)據(jù)在傳輸過程中是分段的,HttpObjectAggregator可以將多個(gè)段聚合pipeline.addLast(new HttpObjectAggregator(8192));//websocketServerProtocolHandler,將http協(xié)議升級(jí)為ws協(xié)議,瀏覽器請(qǐng)求時(shí)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("服務(wù)器已經(jīng)開啟......");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="發(fā)送消息" onclick="send(this.form.message.value)"><textarea id="responseText" name="responseText" style="height: 300px;width: 300px;"></textarea><input type="button" value="清空內(nèi)容" onclick="document.getElementById('responseText').value=''"></form><script>var socket;if (window.WebSocket) {socket = new WebSocket("ws://localhost:8888/hello");//接收服務(wù)器消息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 = "連接開啟......";}//連接關(guān)閉socket.onclose = function (ev) {var rt = document.getElementById("responseText");rt.value = rt.value + "\n" + "連接關(guān)閉了......";}} else {alert("當(dāng)前瀏覽器不支持websocket");}//發(fā)送消息function send(message) {if (!window.WebSocket) {return;}if (socket.readyState == WebSocket.OPEN) {socket.send(message);} else {alert("連接沒有開啟");}}</script></body> </html>

3 測(cè)試

關(guān)閉瀏覽器后:

總結(jié)

以上是生活随笔為你收集整理的Netty集成WebSocket实现客户端、服务端长连接的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。