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. Alpha_6

    一. 站立式会议照片 二. 工作进展 (1) 昨天已完成的工作 a. 修改设计图的小毛病 b. 补签卡页面 c. 实现我的,我的卡包,卡片细节功能页面,并可预览 d. 已实现“番茄钟_数据统计”页面和 ...

  2. css 三角形空心三角形的简单实现

    <style> #talkbubble { width: 120px; height: 80px; position: relative; -moz-border-radius: 10px ...

  3. restframework框架写api中的个人理解以及碰到的问题

    1.明确处理对象,在restframework的处理过程当中,如果是针对model写视图的话,queryset是要待展示的对象集,serializer_class是对每一个对象的所要使用的处理方式. ...

  4. Shell: sh,bash,csh,tcsh等shell的区别(转)

    转载自:http://zhidao.baidu.com/question/493376840.html, http://blog.sina.com.cn/s/blog_71261a2d0100wmbj ...

  5. 【转】SetWindowText 的用法

    SetWindowTextW表示设置的字符串是WCHAR (双字节字符 )SetWindowTextA表示设置的字符串是CHAR (单字节字符 )SetWindowText表示设置的字符串是自动匹配当 ...

  6. 三、Linux_环境变量

    环境变量配置: # 每次进入命令都要重新source /etc/profile 才能生效? # 解决办法:将环境变量放置到~/.bashrc文件中 $ vim ~/.bashrc # 在里面添加相关的 ...

  7. tree - 列出树状目录结构

    tree - list contents of directories in a tree-like format. 树状显示目录结构 常用格式: tree [option] [directory] ...

  8. 发布WS接口与实现WS接口[小列子]

    webservice简介:Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间, ...

  9. 使用CEfSharp之旅(8)CEFSharp 使用代理 更换位置IP

    直接上代码: var settings = new CefSettings(); settings.CachePath = "cache"; settings.CefCommand ...

  10. wordpress模板加载顺序汇总

    我们要创建一个新的wordpress模板需要先了解有哪些页面模板,这些页面模板的文件是什么?它们是怎么工作的?下面ytkah汇总了一些常用的wordpress模板结构方便大家查找 首页 首先WordP ...