Netty 实现 websocket
现在网上网站为了实现推送基本都采用轮询的方式,比较新的轮询技术是comet,采用ajax,但是还是得发送请求,为了解决html效率低下的问题,html5定义了websocket协议。
服务端代码:
import java.util.concurrent.TimeUnit;import org.apache.activemq.util.TimeUtils;import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; 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.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.stream.ChunkedWriteHandler;public class WebSocketServer {public void bind(int port) throws Exception {EventLoopGroup parentGroup = new NioEventLoopGroup();EventLoopGroup childGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(parentGroup, childGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch)throws Exception {ch.pipeline().addLast("http-codec",new HttpServerCodec());ch.pipeline().addLast("aggregator",new HttpObjectAggregator(65536));ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());ch.pipeline().addLast("handler",new WebSocketServerHandler());}});Channel f = b.bind(port).sync().channel();f.closeFuture().sync();} finally{parentGroup.shutdownGracefully();childGroup.shutdownGracefully();}}/*** @param args*/public static void main(String[] args) throws Exception{// TODO Auto-generated method stubnew WebSocketServer().bind(8080);}}
handler
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; import io.netty.util.CharsetUtil;import java.util.Date;public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {private WebSocketServerHandshaker handshaker;@Overrideprotected void messageReceived(ChannelHandlerContext ctx, Object msg)throws Exception {// TODO Auto-generated method stubif(msg instanceof FullHttpRequest){handleHttpRequest(ctx, (FullHttpRequest)msg);}else if(msg instanceof WebSocketFrame){handleWebSocketFrame(ctx, (WebSocketFrame) msg);}}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {cause.printStackTrace();ctx.close();}private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception{System.out.println("handleHttpRequest");if(!req.decoderResult().isSuccess() || !"websocket".equals(req.headers().get("Upgrade"))){sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory("ws://localhost:8080/websocket", null, false);handshaker = factory.newHandshaker(req);if(handshaker == null){WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());}else{handshaker.handshake(ctx.channel(), req);}}private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){System.out.println("handleWebSocketFrame");if(frame instanceof CloseWebSocketFrame){handshaker.close(ctx.channel(), (CloseWebSocketFrame)frame.retain());return;}if(frame instanceof PingWebSocketFrame){ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));return;}if(!(frame instanceof TextWebSocketFrame)){throw new UnsupportedOperationException(String.format("%s frame types not support", frame.getClass().getName()));}String req = ((TextWebSocketFrame) frame).text();System.out.println(String.format("%s received %s", ctx.channel(), req));for(int i = 0; i < 10; i++){ctx.channel().writeAndFlush(new TextWebSocketFrame(req+",欢迎使用Netty Websocket服务,现在时刻:" + new Date().toString()));try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) throws Exception{if(res.status().code() != 200){ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),CharsetUtil.UTF_8);res.content().writeBytes(buf);buf.release();HttpHeaderUtil.setContentLength(res, res.content().readableBytes());}ChannelFuture f = ctx.channel().writeAndFlush(res);if(!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200){f.addListener(ChannelFutureListener.CLOSE);}}}
html调用:
<html><head><meta charset="utf-8">Netty Socket时间服务器</head><body><script type="text/javascript">var socket;if(!window.WebSocket){window.WebSocket = window.MozWebSocket;}if(window.WebSocket){socket = new WebSocket("ws://localhost:8080/websocket");socket.onmessage = function(event){var ta = document.getElementById("responseText");ta.value = "";ta.value = event.data;};socket.onopen = function(event){var ta = document.getElementById("responseText");ta.value ="打开websocket服务正常,浏览器支持websocket"; };socket.onclose = function(event){var ta = document.getElementById("responseText");ta.value = "";ta.value = "websocket关闭";};}else{alert("抱歉,浏览器不支持websocket");}function send(msg){if(socket.readyState = WebSocket.OPEN){socket.send(msg);}else{alert("没有建立连接");}}</script><form><input type="text" name="message" value="Netty最佳"/><input type="button" value="发送websocket请求信息" onclick="send(this.form.message.value)"/><hr color="blue"><textarea id="responseText" style="width:500px;height:300px"></textarea></form></body> </html>
转载于:https://www.cnblogs.com/momofeng/p/5482827.html
Netty 实现 websocket相关推荐
- [源码和文档分享]基于Netty和WebSocket的Web聊天室
一.背景 伴随着Internet的发展与宽带技术的普及,人们可以通过Internet交换动态数据,展示新产品,与人进行沟通并进行电子商务贸易.作为构成网站的重要组成部分,留言管理系统为人们的交流提供了 ...
- Netty之WebSocket和四种IO介绍
Netty简介 一.什么是netty? 高性能 事件驱动 异步非堵塞 基于NIO的客户端,服务器端编程框架 稳定性和伸缩性 二.Netty的使用场景 高性能领域 多线程并发领域 异步通信领域 ...
- 京东到家基于netty与websocket的实践
作者:李天翼,软件开发工程师,任职于达达京东到家后台研发团队,负责订单流程的开发工作. 背景 在京东到家商家中心系统中,商家提出在 Web 端实现自动打印的需求,不需要人工盯守点击打印,直接打印小票, ...
- 基于netty的websocket协议实现
基于netty的websocket协议实现 背景 1.启动服务端 2.测试服务端和客户端效果 背景 项目中使用到了websocket,所以查阅相关资料,完成了一个基于netty的websocket的实 ...
- 简易 IM 双向通信电脑端 GUI 应用——基于 Netty、WebSocket、JavaFX 、多线程技术等
简易 IM 双向通信电脑端 GUI 应用--基于 Netty.WebSocket.JavaFX .多线程技术等 说明 运行效果 核心代码 完整代码 参考知识 说明 这是一款使用 Netty 来实现 ...
- netty系列之:使用netty搭建websocket客户端
文章目录 简介 浏览器客户端 netty对websocket客户端的支持 WebSocketClientHandshaker WebSocketClientCompressionHandler net ...
- netty系列之:使用netty搭建websocket服务器
文章目录 简介 netty中的websocket websocket的版本 FrameDecoder和FrameEncoder WebSocketServerHandshaker WebSocketF ...
- netty 游戏服务器框图_基于Netty和WebSocket协议实现Web端自动打印订单服务方法与流程...
本发明涉及电子商务技术领域,尤其涉及一种基于netty和websocket协议实现web端自动打印订单服务方法. 背景技术: 电子商务是以信息网络技术为手段,以商品交换为中心的商务活动:也可理解为在互 ...
- 基于netty搭建websocket,实现消息的主动推送
基于netty搭建websocket,实现消息的主动推送 rpf_siwash https://www.jianshu.com/p/56216d1052d7 netty是由jboss提供的一款开源框架 ...
- Netty -Netty心跳检测机制案例,Netty通过WebSocket编程实现服务器和客户端长链接
Netty心跳检测机制案例 案例要求 编写一个Netty心跳检测机制案例,当服务器超过3秒没有读时,就提示读空闲 当服务器超过5秒没有写操作时,提示写空闲 服务器超过7秒没有读或者写操作时,就提示读写 ...
最新文章
- GPU运行Tensorflow详细教程及错误解决
- python多态的概念_Python 多态
- NLP-基础知识-001
- Android实现数据存储技术
- 数据库面试题【十三、大表数据查询,怎么优化】
- 前端基础-html-表格的基本标签和相关属性
- ubuntu16.04 安装cuda9.0+cudnn7.0.5+tensorflow+nvidia-docker配置GPU服务
- 开博客了,大家好,这是ATHENS的博客。
- 什么是代码,源文件、编辑和编译?
- FxFactory 7 Mac版(Mac视觉特效插件包)
- 基于WeLink开发的智慧云OA系统获奖啦!
- linux系统配置sftp服务器,linux配置sftp服务器配置
- 好用的思维导图软件有哪些
- Hadoop源代码分析(完整图文版) part 1
- ui设计线上培训怎么样?ui设计线上与线下的区别?
- Xilinx RS编码IP核仿真验证
- SQL Server 2008 Integration Services 用代理加入job的例子
- 服务网格除了 Istio,其实你还可以有其它 8 种选择
- 【思路】扫雷MINE
- 数独解法Python
热门文章
- Windows用管理员方式启动cmd (全面)
- 【工具类】分布式文件存储-FastDFS
- SQL SERVER 创建GHUID命令:select newid();
- Rabbit MQ 学习笔记(3)角色列表
- oc中代理的简单运用
- 弹指之间 -- Waltz
- Linux内核链表实现剖析
- NET Core微服务之路:自己动手实现Rpc服务框架,基于DotEasy.Rpc服务框架的介绍和集成...
- linked-list-cycle-ii (数学证明)
- 015PHP文件处理——文件处理flock 文件锁定 pathinfo realpath tmpfile tempname