Netty集成WebSocket实现客户端、服务端长连接
生活随笔
收集整理的這篇文章主要介紹了
Netty集成WebSocket实现客户端、服务端长连接
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 概述
(1) Http協(xié)議是無(wú)狀態(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) 客戶(hù)端瀏覽器和服務(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()));}/*** 客戶(hù)端連接后*/@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());}/***客戶(hù)端斷開(kāi)連接時(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());//以塊的方式寫(xiě)pipeline.addLast(new ChunkedWriteHandler());//http數(shù)據(jù)在傳輸過(guò)程中是分段的,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)開(kāi)啟......");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;}//連接開(kāi)啟socket.onopen = function (ev) {var rt = document.getElementById("responseText");rt.value = "連接開(kāi)啟......";}//連接關(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("連接沒(méi)有開(kāi)啟");}}</script></body> </html>3 測(cè)試
關(guān)閉瀏覽器后:
總結(jié)
以上是生活随笔為你收集整理的Netty集成WebSocket实现客户端、服务端长连接的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Arduino(MEGA2560)最小系
- 下一篇: windows7配置java环境变量