Netty对WebSocket的支持
WebSocket长连接
一、创建服务端代码
1、MyServer 类
public class MyServer {
public static void main(String[] args) throws Exception{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{ ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO)) //增加日志处理器
.childHandler(new WebSocketChannelInitializer()); ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(8899)).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
2、WebSocketChannelInitializer 类
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel>{ protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandle());
}
}
3、TextWebSocketFrameHandle 类
public class TextWebSocketFrameHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
CommonUtil.println("收到消息:" + msg.text());
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now()));
} @Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
CommonUtil.println("handlerAdded:" +ctx.channel().id().asLongText());
} @Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
CommonUtil.println("handlerRemoved:" +ctx.channel().id().asLongText());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
CommonUtil.println("异常发生");
ctx.close();
}
}
二、编写客户端WebSocket代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<script type="text/javascript"> var socket; if(window.WebSocket){
socket = new WebSocket("ws://localhost:8899/ws");
socket.onmessage = function (event) {
var ta = document.getElementById("responseText");
ta.value = ta.value + "\n" + event.data;
}
socket.onopen = function (event) {
var ta = document.getElementById("responseText");
ta.value = "连接开启"; } socket.onclose = function (event) {
var ta = document.getElementById("responseText");
ta.value = ta.value + "\n" + "连接关闭!";
} }else {
alert("浏览器不支持WebSocket")
} function send(message) {
if(!window.WebSocket){
return;
}
if(socket.readyState == WebSocket.OPEN){
socket.send(message);
}else{
alert("连接尚未开启");
}
} </script>
<form onsubmit="return false">
<textarea name="message" style="width: 400px ; height: 200px;" ></textarea> <input type="button" value="发送数据" onclick="send(this.form.message.value)"> <h3>服务端输出:</h3> <textarea id="responseText" style="width: 400px ; height: 300px;" ></textarea> <input type="button" value="清空内容" onclick="javascript: document.getElementById('responseText').value=''">
</form>
</body>
</html>
三、测试
1、启动服务端
2、打开页面 http://localhost:7080/test.html
可以看到,连接开启。
服务端输出如下图:
四、进入页面的开发者模式
可以发现,
1、Status Code:101 Switching Protocols。 原来是Http的,切换成Socket
2、请求头: Upgrade:websocket
虽然请求发送的ws,但是要先发送的http请求建立连接,连接建立好后,将http升级到websockent协议上
五、测试发送消息
整个请求建立在webSocket协议之上。
六、连接关闭
当服务端停掉后,可以收到连接关闭。
七、websocket的请求和接收
如下图: Hello是请求, 服务器时间是接收
Netty对WebSocket的支持的更多相关文章
- Netty对WebSocket的支持(五)
Netty对WebSocket的支持(五) 一.WebSocket简介 在Http1.0和Http1.1协议中,我们要实现服务端主动的发送消息到网页或者APP上,是比较困难的,尤其是现在IM(即时通信 ...
- Netty 搭建 WebSocket 服务端
一.编码器.解码器 ... ... @Autowired private HttpRequestHandler httpRequestHandler; @Autowired private TextW ...
- netty系列之:使用netty搭建websocket客户端
目录 简介 浏览器客户端 netty对websocket客户端的支持 WebSocketClientHandshaker WebSocketClientCompressionHandler netty ...
- Netty 实现 WebSocket 聊天功能
上一次我们用Netty快速实现了一个 Java 聊天程序(见http://www.waylau.com/netty-chat/).现在,我们要做下修改,加入 WebSocket 的支持,使它可以在浏览 ...
- MQTT协议笔记之mqtt.io项目Websocket协议支持
前言 MQTT协议专注于网络.资源受限环境,建立之初不曾考虑WEB环境,倒也正常.虽然如此,但不代表它不适合HTML5环境. HTML5 Websocket是建立在TCP基础上的双通道通信,和TCP通 ...
- netty系列之:使用netty搭建websocket服务器
目录 简介 netty中的websocket websocket的版本 FrameDecoder和FrameEncoder WebSocketServerHandshaker WebSocketFra ...
- Jmeter中Websocket协议支持包的使用
Jmeter中Websocket协议支持包的使用(转) 参考的来源是国外一篇文章,已经整理成pdf格式(http://yunpan.cn/cFzwiyeQDKdh3 (提取码:9bcf)) 转自:ht ...
- jmeter关联Websocket包支持
消息文本发送内容采用的是websocket方式进行消息握手的,一次使用到WEBSOCKET包支持 对于它的介绍和使用如下: 一.首先,我们需要准备Jmeter的WebSocket协议的支持插件:JMe ...
- 使用Netty做WebSocket服务端
使用Netty搭建WebSocket服务器 1.WebSocketServer.java public class WebSocketServer { private final ChannelGro ...
随机推荐
- ORACLE ASMLIB
ORACLE ASMLIB This blog post is more of a note for myself on configuring ASMLib. ASMLib is an opti ...
- springcloud中gateway的实际应用
之前我一直用的是Zuul网关,用过gateway以后感觉比Zuul功能还是强大很多. Spring Cloud Gateway是基于Spring5.0,Spring Boot2.0和Project R ...
- 根据不同配置.env获取不同的配置文件的配置
env 不同环境 1. 安装扩展 composer require vlucas/phpdotenv 2 . 创建文件 .env .env.test .env.production .env.exam ...
- zookeeper 事务日志查看
在version下的日志是二进制文件,查看需要转换 创建/data/middleware/zookeeper-3.4.14/translog.sh 脚本 格式化命令: java -classpath ...
- 17,Flask-admin后台管理系统总结
导入包 from flask_admin import Admin,BaseView,expose,AdminIndexView from flask_admin.contrib.sqla impor ...
- 用session防止网站页面被频繁刷新
session防止网站页面频繁被刷新 <?php //公司网站老是受到攻击,这是之前在网上看到的一个用session防止IP频繁访问的方法,我们公司用的是Memcache,都差不多,就是存储方式 ...
- 业余时间折腾了个微信小程序版本的街机游戏模拟器(吾爱街机),8090后的童年回忆,欢迎大家体验
好多年没来博客园了,有段时间想玩街机游戏,发现都需要下载安装,现在小程序这么流行,是不是可以集成到小程序里(无需下载,在线玩),出于这想法,就业余时间折腾了下,分享给大家,偶尔可以回味畅玩下. 中间遇 ...
- scrapy框架爬取智联招聘网站上深圳地区python岗位信息。
爬取字段,公司名称,职位名称,公司详情的链接,薪资待遇,要求的工作经验年限 1,items中定义爬取字段 import scrapy class ZhilianzhaopinItem(scrapy.I ...
- python使用print写文件
刚刚看sumo的官方教程,有一段代码是生成配置文件,发现python中的print函数也可以写文件. with open("data/cross.rou.xml", "w ...
- js插件---webuploader 使用(lavarel中使用)
js插件---webuploader 使用(lavarel中使用) 一.总结 一句话总结: 多去看几个具体使用的实例,很多blog教程都有坑,多看几个交叉印证可以没那么多坑 1.webuploader ...