前面2文

基于http的netty demo

基于socket的netty demo

讲了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的更多相关文章

  1. 基于socket的netty demo

    前面一文说了 基于http的netty demo 和http不一样,http可以用浏览器来充当客户端调用,所以基于socket的netty,必须要编写客户端和服务器的代码 实现功能: 客户端给服务器发 ...

  2. 基于websocket vue 聊天demo 解决方案

    基于websocket vue 聊天demo 解决方案 demo 背景 电商后台管理的客服 相关技术 vuex axios vue websocket 聊天几种模型 一对一模型 一对一 消息只一个客户 ...

  3. 基于http的netty demo

    1.引入netty的pom <dependency> <groupId>io.netty</groupId> <artifactId>netty-all ...

  4. Netty 系列八(基于 WebSocket 的简单聊天室).

    一.前言 之前写过一篇 Spring 集成 WebSocket 协议的文章 —— Spring消息之WebSocket ,所以对于 WebSocket 协议的介绍就不多说了,可以参考这篇文章.这里只做 ...

  5. 第一节:.Net版基于WebSocket的聊天室样例

    一. 说在前面的话 该篇文章为实时通讯系列的第一节,基于WebSocket编写了一个简易版聊天样例,主要作用是为引出后面SignalR系列的用法及其强大方便之处,通过这个样例与后续的SignalR对比 ...

  6. Ext JS学习第十六天 事件机制event(一) DotNet进阶系列(持续更新) 第一节:.Net版基于WebSocket的聊天室样例 第十五节:深入理解async和await的作用及各种适用场景和用法 第十五节:深入理解async和await的作用及各种适用场景和用法 前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、G

    code&monkey   Ext JS学习第十六天 事件机制event(一) 此文用来记录学习笔记: 休息了好几天,从今天开始继续保持更新,鞭策自己学习 今天我们来说一说什么是事件,对于事件 ...

  7. 基于WebSocket和SpringBoot的群聊天室

    引入 普通请求-响应方式:例如Servlet中HttpServletRequest和HttpServletResponse相互配合先接受请求.解析数据,再发出响应,处理完成后连接便断开了,没有数据的实 ...

  8. workerman-chat(PHP开发的基于Websocket协议的聊天室框架)(thinkphp也是支持socket聊天的)

    workerman-chat(PHP开发的基于Websocket协议的聊天室框架)(thinkphp也是支持socket聊天的) 一.总结 1.下面链接里面还有一个来聊的php聊天室源码可以学习 2. ...

  9. 基于 WebSocket 实现 WebGL 3D 拓扑图实时数据通讯同步(二)

    我们上一篇<基于 WebSocket 实现 WebGL 3D 拓扑图实时数据通讯同步(一)>主要讲解了如何搭建一个实时数据通讯服务器,客户端与服务端是如何通讯的,相信通过上一篇的讲解,再配 ...

随机推荐

  1. 第11.7节 Python正则表达式的字符串结尾匹配模式及元字符“$”功能介绍

    符号"$"表示匹配字符串的结尾,即字符串的结尾满足匹配模式的要求. 在 MULTILINE 模式(搜索标记中包含re.MULTILINE,关于搜索标记的含义请见<第11.2节 ...

  2. Making Games with Python & Pygame 中文翻译

    Making Games with Python & Pygame 用Pygame做游戏 第1章-安装python和pygame 原文作者:Al Sweigart 翻译:bigbigli/李超 ...

  3. do{}while(false)的用法

    do{}while(false): 在工作中我们能经常发现有人写 do{}while(false)  这样的代码,初看时让人迷惑不解,按照上面的语法 do{}while(false) 这样 do{} ...

  4. springmvc中使用文件上传功能

    项目代码:https://github.com/PeiranZhang/springmvc-fileupload Servlet3.0之前使用文件上传功能 Servlet3.0之前需要使用common ...

  5. log4j配置获取系统属性及默认值

    一.使用场景 1.因某些原因,我们可能将log4j中的配置变量化,进行动态获取 2.动态获取内容不存在时,我们希望能够赋上通用的值 二.语法 单变量: ${前缀:变量:-默认值} 如: ${sys:i ...

  6. sychronized的实现原理和应用

    一.synchronized的使用 1.1修饰方法 public synchronized void method() { // todo } 1.2修饰代码块 public void run() { ...

  7. 啊!Java虚方法

     什么是Java的虚方法呢,我们首先看看什么是虚函数 虚函数 百度百科的解释为: 在某基类中声明为 virtual 并在一个或多个派生类中被重新定义的[成员函数],用法格式为:virtual 函数返回 ...

  8. matplotlib的学习12-Subplot 多合一显示

    import matplotlib.pyplot as plt # matplotlib 是可以组合许多的小图, 放在一张大图里面显示的. 使用到的方法叫作 subplot. plt.figure() ...

  9. go-slice实现的使用和基本原理

    目录 摘要 Slice数据结构 使用make创建Slice 使用数组创建Slice Slice 扩容 Slice Copy 特殊切片 总结 参考 你的鼓励也是我创作的动力 Posted by 微博@Y ...

  10. Maven史上最全的pom.xml详解

    下面主要是借鉴 官网的资料 收集而来 主要是为了讲解,用到的很少,但是还是需要了解 ,重点是方便查验资料 <project xmlns="http://maven.apache.org ...