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. Telnet入侵WindowsXP

    上一章,采用图形界面配置.这一节,采用命令方式配置 //修复.bat(掩饰名字) @ echo off //关闭回显 regedit.exe /s start.reg ///s 不打印 net sta ...

  2. 爬取网易云音乐歌手和id

    pip install lxml csv requests from lxml import etree from time import sleep import csv import reques ...

  3. Redis开发与运维学习笔记

    <Redis开发与运维>读书笔记   一.初始Redis 1.Redis特性与优点 速度快.redis所有数据都存放于内存:是用C语言实现,更加贴近硬件:使用了单线程架构,避免了多线程竞争 ...

  4. 【Flask】 python学习第一章 - 4.0 钩子函数和装饰器路由实现 session-cookie 请求上下文

    钩子函数和装饰器路由实现 before_request 每次请求都会触发 before_first_requrest  第一次请求前触发 after_request  请求后触发 并返回参数 tear ...

  5. Python Image库简单处理图像

    直接列举几个常用的函数,可在 http://effbot.org/imagingbook/image.htm 中查看更多相关函数. from PIL import Image import numpy ...

  6. MySQL/MariaDB数据库的冷备份和还原

    MySQL/MariaDB数据库的冷备份和还原 作者:尹正杰  版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.MySQL/MariaDB数据库的备份和还原概述 1>.为什么要备份 为了 ...

  7. poj3268 Silver Cow Party(最短路)

    非常感谢kuangbin专题啊,这道题一开始模拟邻接表做的,反向边不好处理,邻接矩阵的话舒服多了. 题意:给n头牛和m条有向边,每头牛1~n编号,求所有牛中到x编号去的最短路+回来的最短路的最大值. ...

  8. SQL查询结果拼接成字符串

    sqlserver中将查询结果拼接成字符串   #for xml path(param)--将查询结果以xml格式输出 1 select id,name from table1 for xml pat ...

  9. 更新GitHub上自己 Fork 的代码与原作者的项目进度一致

    在GitHub上我们会去fork别人的一个项目,这就在自己的Github上生成了一个与原作者项目互不影响的副本,自己可以将自己Github上的这个项目再clone到本地进行修改,修改后再push,只有 ...

  10. keras中to_categorical()函数解析

    from keras.utils.np_utils import * # 类别向量定义 b = [0, 1, 2, 3, 4, 5, 6, 7, 8] # 调用to_categorical将b按照9个 ...