Springboot2整合netty4.0

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_15153911/article/details/83276645

Springboot2整合netty4.0

在这里插入图片描述

前端:

window.CHAT = {
				socket: null,
				init: function() {
					if (window.WebSocket) {
						CHAT.socket = new WebSocket("ws://192.168.1.10:8088/ws");
						CHAT.socket.onopen = function() {
							console.log("连接建立成功...");
						},
						CHAT.socket.onclose = function() {
							console.log("连接关闭...");
						},
						CHAT.socket.onerror = function() {
							console.log("发生错误...");
						},
						CHAT.socket.onmessage = function(e) {
							console.log("接受到消息:" + e.data);
							var receiveMsg = document.getElementById("receiveMsg");
							var html = receiveMsg.innerHTML;
							receiveMsg.innerHTML = html + "<br/>" + e.data;
						}
					} else {
						alert("浏览器不支持websocket协议...");
					}
				},
				chat: function() {
					var msg = document.getElementById("msgContent");
					CHAT.socket.send(msg.value);
				}
			};
			
			CHAT.init();

后端:整合netty server
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();

	// websocket 基于http协议,所以要有http编解码器
	pipeline.addLast(new HttpServerCodec());
	// 对写大数据流的支持 
	pipeline.addLast(new ChunkedWriteHandler());
	// 对httpMessage进行聚合,聚合成FullHttpRequest或FullHttpResponse
	// 几乎在netty中的编程,都会使用到此hanler
	pipeline.addLast(new HttpObjectAggregator(1024*64));
	
	// ====================== 以上是用于支持http协议    ======================
	
	
	
	// ====================== 增加心跳支持 start    ======================
	// 针对客户端,如果在1分钟时没有向服务端发送读写心跳(ALL),则主动断开
	// 如果是读空闲或者写空闲,不处理
	pipeline.addLast(new IdleStateHandler(8, 10, 12));
	// 自定义的空闲状态检测
	pipeline.addLast(new HeartBeatHandler());
	// ====================== 增加心跳支持 end    ======================
	
	
	
	
	// ====================== 以下是支持httpWebsocket ======================
	
	/**
	 * websocket 服务器处理的协议,用于指定给客户端连接访问的路由 : /ws
	 * 本handler会帮你处理一些繁重的复杂的事
	 * 会帮你处理握手动作: handshaking(close, ping, pong) ping + pong = 心跳
	 * 对于websocket来讲,都是以frames进行传输的,不同的数据类型对应的frames也不同
	 */
	pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
	
	// 自定义的handler
	pipeline.addLast(new ChatHandler());
}

源码下载:http://47.98.237.162/detail/1/181

下载源码后,记住分享哟!

第一步:微信关注公众号艳学网!

第二步:关注后打开菜单“艳辉福利”——“java福利”,转发文章至朋友圈。

长按自动识别二维码,即可关注微信公众号“艳学网”
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sinat_15153911/article/details/83276645