基于websocket的netty demo
前面2文
讲了netty在http和socket的使用,下面讲讲netty如何使用websocket
websocket是html5提出来的一个东西,功能很强大,可以支持长连接,实现服务器向客户端的通信,这里不做过多的介绍,只说说netty如何使用websocket作为协议来通信
这里采用表单提交的时候,使用websocket的方式提交,具体请看代码:
ps:我这里的代码架构是这样的
服务器代码:
1 package com.bill.websocketdemo;
2
3
4 import io.netty.bootstrap.ServerBootstrap;
5 import io.netty.channel.ChannelFuture;
6 import io.netty.channel.EventLoopGroup;
7 import io.netty.channel.nio.NioEventLoopGroup;
8 import io.netty.channel.socket.nio.NioServerSocketChannel;
9 import io.netty.handler.logging.LogLevel;
10 import io.netty.handler.logging.LoggingHandler;
11
12 public class WebSocketServer {
13
14 public static void main(String[] args) throws Exception {
15 EventLoopGroup bossGroup = new NioEventLoopGroup();
16 EventLoopGroup workerGroup = new NioEventLoopGroup();
17
18 try{
19 ServerBootstrap serverBootstrap = new ServerBootstrap();
20 serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
21 handler(new LoggingHandler(LogLevel.INFO)).childHandler(new WebSocketChannelInitializer());
22
23 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
24 channelFuture.channel().closeFuture().sync();
25 } finally {
26 bossGroup.shutdownGracefully();
27 workerGroup.shutdownGracefully();
28 }
29 }
30 }
31
32 package com.bill.websocketdemo;
33
34
35 import io.netty.channel.ChannelHandlerContext;
36 import io.netty.channel.SimpleChannelInboundHandler;
37 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
38
39 public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
40
41 @Override
42 protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
43 System.out.println("收到消息:" + textWebSocketFrame.text());
44 channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器随机数:" + Math.random()));
45 }
46
47 @Override
48 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
49 System.out.println("handlerAdded!!!");
50 }
51
52 @Override
53 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
54 System.out.println("handlerRemoved!!!");
55 }
56 }
57
58 package com.bill.websocketdemo;
59
60
61 import io.netty.channel.ChannelInitializer;
62 import io.netty.channel.ChannelPipeline;
63 import io.netty.channel.socket.SocketChannel;
64 import io.netty.handler.codec.http.HttpObjectAggregator;
65 import io.netty.handler.codec.http.HttpServerCodec;
66 import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
67 import io.netty.handler.stream.ChunkedWriteHandler;
68
69 public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
70
71 @Override
72 protected void initChannel(SocketChannel socketChannel) throws Exception {
73
74 ChannelPipeline pipeline = socketChannel.pipeline();
75
76 pipeline.addLast(new HttpServerCodec());
77 pipeline.addLast(new ChunkedWriteHandler());
78 pipeline.addLast(new HttpObjectAggregator(8192));
79 pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
80
81 pipeline.addLast(new WebSocketHandler());
82
83 }
84 }
HTML代码:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>websocket</title>
6 </head>
7 <body>
8
9 <script type="text/javascript">
10 var socket;
11 if(window.WebSocket) {
12 socket = new WebSocket("ws://localhost:8899/hello");
13 socket.onmessage = function (event) {
14 var ta = document.getElementById("resp");
15 ta.value = ta.value + "\n" + event.data;
16 }
17
18 socket.onopen = function (event) {
19 var ta = document.getElementById("resp");
20 ta.value = "连接接开启!";
21 }
22
23 socket.onclose = function (event) {
24 var ta = document.getElementById("resp");
25 ta.value = ta.value + "\n" + "连接关闭!";
26 }
27 } else {
28 alert("浏览器不支持websocket");
29 }
30
31 function send(msg) {
32 if(!window.WebSocket) {
33 return;
34 }
35
36 if(socket.readyState == WebSocket.OPEN) {
37 socket.send(msg);
38 } else {
39 alert("连接未开启!")
40 }
41 }
42
43 </script>
44
45 <form onsubmit="return false;">
46
47 <textarea id="message" style="width: 400px; height: 200px"></textarea>
48 <input type="button" value="发送数据" onclick="send(this.form.message.value)">
49
50 <h3> 服务器输出:</h3>
51
52 <textarea id="resp" style="width: 400px; height: 300px"></textarea>
53 <input type="button" onclick="javascript: document.getElementById('resp').value = ''" value="清空内容">
54 </form>
55
56
57 </body>
58 </html>
请注意:
运行的时候,先执行WebSocketServer的main方法,然后再run src/main/webapp/test.html ,这样 idea会自动启动一个页面
启动完服务器后,会在浏览器上看到页面:
服务器出现信息:
发送数据:
服务器:
完整代码下载:
https://download.csdn.net/download/mweibiao/10551574
基于websocket的netty demo的更多相关文章
- 基于socket的netty demo
前面一文说了 基于http的netty demo 和http不一样,http可以用浏览器来充当客户端调用,所以基于socket的netty,必须要编写客户端和服务器的代码 实现功能: 客户端给服务器发 ...
- 基于websocket vue 聊天demo 解决方案
基于websocket vue 聊天demo 解决方案 demo 背景 电商后台管理的客服 相关技术 vuex axios vue websocket 聊天几种模型 一对一模型 一对一 消息只一个客户 ...
- 基于http的netty demo
1.引入netty的pom <dependency> <groupId>io.netty</groupId> <artifactId>netty-all ...
- Netty 系列八(基于 WebSocket 的简单聊天室).
一.前言 之前写过一篇 Spring 集成 WebSocket 协议的文章 —— Spring消息之WebSocket ,所以对于 WebSocket 协议的介绍就不多说了,可以参考这篇文章.这里只做 ...
- 第一节:.Net版基于WebSocket的聊天室样例
一. 说在前面的话 该篇文章为实时通讯系列的第一节,基于WebSocket编写了一个简易版聊天样例,主要作用是为引出后面SignalR系列的用法及其强大方便之处,通过这个样例与后续的SignalR对比 ...
- Ext JS学习第十六天 事件机制event(一) DotNet进阶系列(持续更新) 第一节:.Net版基于WebSocket的聊天室样例 第十五节:深入理解async和await的作用及各种适用场景和用法 第十五节:深入理解async和await的作用及各种适用场景和用法 前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、G
code&monkey Ext JS学习第十六天 事件机制event(一) 此文用来记录学习笔记: 休息了好几天,从今天开始继续保持更新,鞭策自己学习 今天我们来说一说什么是事件,对于事件 ...
- 基于WebSocket和SpringBoot的群聊天室
引入 普通请求-响应方式:例如Servlet中HttpServletRequest和HttpServletResponse相互配合先接受请求.解析数据,再发出响应,处理完成后连接便断开了,没有数据的实 ...
- workerman-chat(PHP开发的基于Websocket协议的聊天室框架)(thinkphp也是支持socket聊天的)
workerman-chat(PHP开发的基于Websocket协议的聊天室框架)(thinkphp也是支持socket聊天的) 一.总结 1.下面链接里面还有一个来聊的php聊天室源码可以学习 2. ...
- 基于 WebSocket 实现 WebGL 3D 拓扑图实时数据通讯同步(二)
我们上一篇<基于 WebSocket 实现 WebGL 3D 拓扑图实时数据通讯同步(一)>主要讲解了如何搭建一个实时数据通讯服务器,客户端与服务端是如何通讯的,相信通过上一篇的讲解,再配 ...
随机推荐
- django+channels+dephne实现websockrt部署
当你的django项目中使用channels增加了websocket功能的时候,在使用runserver命令启动时,既可以访问http请求,又可以访问websocket请求.但是当你使用uWSGI+n ...
- 记一次MongoDB的失败导出
MongoDB用的是阿里云的,今天想着把原来的数据导出进行一次去重处理,整理下数据.操作了好几个小时,还是未能成功导出. MongoDB用的是阿里云的专有网络连接,本想通过公网直接访问,申请了公网地址 ...
- Python模块是否支持自定义属性使用双下划线开头和结尾?
我们知道在Python中,变量名类似__xxx__的,也就是以双下划线开头并且以双下划线结尾的变量和方法,是特殊变量,特殊变量是可以直接访问的,不是私有变量,所以,一般实例变量和类变量以及方法不能用_ ...
- PyQt(Python+Qt)学习随笔:gridLayout的layoutRowStretch和layoutColumnStretch属性
Qt Designer中网格布局中,layoutRowStretch和layoutColumnStretch两个属性分别设置网格布局中行之间和列之间的拉伸因子,如图: 但是QGridLayout并没有 ...
- [BJDCTF2020]ZJCTF,不过如此 php伪协议, preg_replace() 函数/e模式
转自https://www.cnblogs.com/gaonuoqi/p/12499623.html 题目给了源码 <?php error_reporting(0); $text = $_GET ...
- 项目实战:Qt多通道数据采集系统(通道配置、电压转换、采样频率、通道补偿值、定时采集、导出exel和图表、自动XY轴、隐藏XY轴、实时隐藏显示通道)
需求 1.通道使能.选择.更改通道名称.设置显示颜色 2.采样率可设置(Sa/s/chj) 3.单位换算,按照给定的进行换算 4.对通道可进行设置补偿值 5.通道取消可动态显示和隐藏,并可 ...
- 笔记-Recursive Queries
Recursive Queries \[m_{l,r}=\textrm{id}(\max_{i=l}^r a_i)\\ f(l,r)= \begin{cases} (r-l+1)+f(l,m_{l,r ...
- 搭建yum仓库服务器
环境:服务端centos6.9 客户端要求 能上网(可以ping通baidu.com) 1.yum的配置文件信息在/etc/yum.repos.d/下,我们配置的是自己的网络yum源,所以这些文件我们 ...
- jmeter__问题记录,中文乱码问题(json参数化)
这种情况在jmeter3.0的版本中才会产生,注意:这不是乱码,而是由于3.0中优化body data后,使用默认的字体(Consolas)不支持汉字的显示.这样的情况可以这样调整:进入jmeter. ...
- # spring boot + mybatis 读取数据库
spring boot + mybatis 读取数据库 创建数据库 use testdb; drop table if exists t_city; create table t_city( id i ...