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的支持的更多相关文章

  1. Netty对WebSocket的支持(五)

    Netty对WebSocket的支持(五) 一.WebSocket简介 在Http1.0和Http1.1协议中,我们要实现服务端主动的发送消息到网页或者APP上,是比较困难的,尤其是现在IM(即时通信 ...

  2. Netty 搭建 WebSocket 服务端

    一.编码器.解码器 ... ... @Autowired private HttpRequestHandler httpRequestHandler; @Autowired private TextW ...

  3. netty系列之:使用netty搭建websocket客户端

    目录 简介 浏览器客户端 netty对websocket客户端的支持 WebSocketClientHandshaker WebSocketClientCompressionHandler netty ...

  4. Netty 实现 WebSocket 聊天功能

    上一次我们用Netty快速实现了一个 Java 聊天程序(见http://www.waylau.com/netty-chat/).现在,我们要做下修改,加入 WebSocket 的支持,使它可以在浏览 ...

  5. MQTT协议笔记之mqtt.io项目Websocket协议支持

    前言 MQTT协议专注于网络.资源受限环境,建立之初不曾考虑WEB环境,倒也正常.虽然如此,但不代表它不适合HTML5环境. HTML5 Websocket是建立在TCP基础上的双通道通信,和TCP通 ...

  6. netty系列之:使用netty搭建websocket服务器

    目录 简介 netty中的websocket websocket的版本 FrameDecoder和FrameEncoder WebSocketServerHandshaker WebSocketFra ...

  7. Jmeter中Websocket协议支持包的使用

    Jmeter中Websocket协议支持包的使用(转) 参考的来源是国外一篇文章,已经整理成pdf格式(http://yunpan.cn/cFzwiyeQDKdh3 (提取码:9bcf)) 转自:ht ...

  8. jmeter关联Websocket包支持

    消息文本发送内容采用的是websocket方式进行消息握手的,一次使用到WEBSOCKET包支持 对于它的介绍和使用如下: 一.首先,我们需要准备Jmeter的WebSocket协议的支持插件:JMe ...

  9. 使用Netty做WebSocket服务端

    使用Netty搭建WebSocket服务器 1.WebSocketServer.java public class WebSocketServer { private final ChannelGro ...

随机推荐

  1. 笔谈kxmovie开源播放器库的使用

    开源播放器项目 kxmovie(https://github.com/kolyvan/kxmovie),现在仍然是很多刚开始接触播放器开发的程序员的参照范本.以下是我操作kxmovie项目的过程: ( ...

  2. java requestmapping中关于路径的问题

    需要这种url写的方式才能映射

  3. Apache 正向代理与反向代理配置

    Apache提供了 mod_proxy 模块用于提供代理服务,能够支持的包括正向代理.反向代理.透明代理.缓存.负载均衡,HTTP代理.FTP代理.SSL代理等若干强大的功能. 配置代理方法很简单那, ...

  4. 图记 2016.1.7 获取本地图片、Bitmap转image

    这几天完成的内容有: 1.“添加图片”按钮 2.添加图片功能 遇到的问题: 我想要将添加图片按钮放在右下角,所以采用了相对布局,但是问题随之二来,因为将导航栏设置成了半透明,所以图片放到右下角之后,半 ...

  5. Deployment

    Deployment RC是kubernetes中的一个核心概念,Deployment 是新一代的RC,除了拥有RC的功能外,还具备一下特性: 支持事件和状态查看:可以查看Deployment升级的状 ...

  6. Codeforces C. Elections(贪心枚举三分)

    题目描述: C. Elections time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  7. WinForm 捕获异常 Application.ThreadException + AppDomain.CurrentDomain.UnhandledException

     WinForm 捕获未处理的异常,可以使用Application.ThreadException 和AppDomain.CurrentDomain.UnhandledException事件 WinF ...

  8. [Codeforces 1265E]Beautiful Mirrors

    Description 题库链接 一共有 \(n\) 个关卡,你初始在第一个关卡.通过第 \(i\) 个关卡的概率为 \(p_i\).每一轮你可以挑战一个关卡.若通过第 \(i\) 个关卡,则进入第 ...

  9. 使用GCOV进行代码覆盖率统计

    GCOV是随GCC一起发布的用于代码覆盖率统计的工具,一般配合其图形化工具LCOV一起使用. 一.安装 GCOV不需要单独安装,LCOV下载后执行sudo make install即可完成安装. 二. ...

  10. 树的点分治 板题 Luogu P3806

    给定一棵有n个点的树 询问树上距离为k的点对是否存在. AC code: #include<bits/stdc++.h> using namespace std; const int MA ...