【Netty】WebSocket
一、前言
前面学习了codec和ChannelHandler之间的关系,接着学习WebSocket。
二、WebSocket
2.1. WebSocket介绍
WebSocket协议允许客户端和服务器随时传输消息,要求他们异步处理接收的消息,而几乎所有的浏览器都支持WebSocket协议,Netty支持WebSocket协议的所有实现,可以在应用中直接使用。
2.2. WebSocket应用示例
下面示例展示了如何使用WebSocket协议实现基于浏览器的实时聊天应用,示例逻辑图如下图所示。

处理逻辑如下
· 客户端发送消息。
· 消息转发至其他所有客户端。
本示例中只实现服务端部分,客户端网页为index.html。
2.3 添加WebSocket支持
升级握手机制可用于从标准HTTP或HTTPS协议切换到WebSocket,使用WebSocket的应用程序以HTTP/S开头,当请求指定URL时将会启动该协议。本应用有如下惯例:如果URL请求以/ ws结尾,我们将使用升级的WebSocket协议,否则,将使用HTTP/S协议,连接升级后,所有数据将使用WebSocket传输。下图展示服务端的逻辑。

1. 处理HTTP请求
首先我们实现处理HTTP请求的组件,该组件将为访问聊天室的页面提供服务,并显示连接的客户端发送的消息。下面是HttpRequestHandler代码,其继承SimpleChannelInboundHandler。
public class HttpRequestHandler
extends SimpleChannelInboundHandler<FullHttpRequest> {
private final String wsUri;
private static final File INDEX;
static {
URL location = HttpRequestHandler.class
.getProtectionDomain()
.getCodeSource().getLocation();
try {
String path = location.toURI() + "index.html";
path = !path.contains("file:") ? path : path.substring(5);
INDEX = new File(path);
} catch (URISyntaxException e) {
throw new IllegalStateException(
"Unable to locate index.html", e);
}
}
public HttpRequestHandler(String wsUri) {
this.wsUri = wsUri;
}
@Override
public void channelRead0(ChannelHandlerContext ctx,
FullHttpRequest request) throws Exception {
if (wsUri.equalsIgnoreCase(request.getUri())) {
ctx.fireChannelRead(request.retain());
} else {
if (HttpHeaders.is100ContinueExpected(request)) {
send100Continue(ctx);
}
RandomAccessFile file = new RandomAccessFile(INDEX, "r");
HttpResponse response = new DefaultHttpResponse(
request.getProtocolVersion(), HttpResponseStatus.OK);
response.headers().set(
HttpHeaders.Names.CONTENT_TYPE,
"text/plain; charset=UTF-8");
boolean keepAlive = HttpHeaders.isKeepAlive(request);
if (keepAlive) {
response.headers().set(
HttpHeaders.Names.CONTENT_LENGTH, file.length());
response.headers().set( HttpHeaders.Names.CONNECTION,
HttpHeaders.Values.KEEP_ALIVE);
}
ctx.write(response);
if (ctx.pipeline().get(SslHandler.class) == null) {
ctx.write(new DefaultFileRegion(
file.getChannel(), 0, file.length()));
} else {
ctx.write(new ChunkedNioFile(file.getChannel()));
}
ChannelFuture future = ctx.writeAndFlush(
LastHttpContent.EMPTY_LAST_CONTENT);
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
private static void send100Continue(ChannelHandlerContext ctx) {
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
ctx.writeAndFlush(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
上述代码用于处理纯HTTP请求,对于WebSocket而言,数据使用帧进行传输,完整的数据包含多帧。
2. 处理WebSocket帧
WebSocket定义了六种帧,如下图所示。

对于聊天应用而言,其包含如下帧:CloseWebSocketFrame、PingWebSocketFrame、PongWebSocketFrame、TextWebSocketFrame。
下面代码展示了用于处理TextWebSocketFrames的ChannelHandler。
public class TextWebSocketFrameHandler
extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private final ChannelGroup group;
public TextWebSocketFrameHandler(ChannelGroup group) {
this.group = group;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx,
Object evt) throws Exception {
if (evt == WebSocketServerProtocolHandler
.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
ctx.pipeline().remove(HttpRequestHandler.class);
group.writeAndFlush(new TextWebSocketFrame(
"Client " + ctx.channel() + " joined"));
group.add(ctx.channel());
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx,
TextWebSocketFrame msg) throws Exception {
group.writeAndFlush(msg.retain());
}
}
3. 初始化ChannelPipeline
为在ChannelPipeline中添加ChannelHandler,需要继承ChannelInitializer并且实现initChannel方法,下面是ChatServerInitializer的代码。
public class ChatServerInitializer extends ChannelInitializer<Channel> {
private final ChannelGroup group;
public ChatServerInitializer(ChannelGroup group) {
this.group = group;
}
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(64 * 1024));
pipeline.addLast(new HttpRequestHandler("/ws"));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandler(group));
}
}
对于使用HTTP协议(升级前)和WebSocket协议(升级后)的管道中的处理器分别如下图所示。


4. Bootstrapping
ChatServer类用于启动服务器并且安装ChatServerInitializer,其代码如下。
public class ChatServer {
private final ChannelGroup channelGroup =
new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
private final EventLoopGroup group = new NioEventLoopGroup();
private Channel channel;
public ChannelFuture start(InetSocketAddress address) {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(createInitializer(channelGroup));
ChannelFuture future = bootstrap.bind(address);
future.syncUninterruptibly();
channel = future.channel();
return future;
}
protected ChannelInitializer<Channel> createInitializer(
ChannelGroup group) {
return new ChatServerInitializer(group);
}
public void destroy() {
if (channel != null) {
channel.close();
}
channelGroup.close();
group.shutdownGracefully();
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Please give port as argument");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final ChatServer endpoint = new ChatServer();
ChannelFuture future = endpoint.start(
new InetSocketAddress(port));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
endpoint.destroy();
}
});
future.channel().closeFuture().syncUninterruptibly();
}
}
上述代码就完成了服务端的所有代码,接着进行测试。
2.4 加密应用
上述代码中可正常进行通信,但是并未加密,首先需要添加SecureChatServerInitializer,其代码如下。
public class SecureChatServerInitializer extends ChatServerInitializer {
private final SslContext context;
public SecureChatServerInitializer(ChannelGroup group,
SslContext context) {
super(group);
this.context = context;
}
@Override
protected void initChannel(Channel ch) throws Exception {
super.initChannel(ch);
SSLEngine engine = context.newEngine(ch.alloc());
ch.pipeline().addFirst(new SslHandler(engine));
}
}
然后添加SecureChatServerInitializer,代码如下。
public class SecureChatServer extends ChatServer {
private final SslContext context;
public SecureChatServer(SslContext context) {
this.context = context;
}
@Override
protected ChannelInitializer<Channel> createInitializer(
ChannelGroup group) {
return new SecureChatServerInitializer(group, context);
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Please give port as argument");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
SelfSignedCertificate cert = new SelfSignedCertificate();
SslContext context = SslContext.newServerContext(
cert.certificate(), cert.privateKey());
final SecureChatServer endpoint = new SecureChatServer(context);
ChannelFuture future = endpoint.start(new InetSocketAddress(port));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
endpoint.destroy();
}
});
future.channel().closeFuture().syncUninterruptibly();
}
}
2.5 测试应用
在编译的classes文件夹中加入index.html(客户端),其中index.html的源码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>
<body>
<script type="text/javascript">
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/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 = "connected!";
};
socket.onclose = function(event) {
var ta = document.getElementById('responseText');
ta.value = ta.value + "connection is shutdown";
};
} else {
alert("your broswer do not support WebSocket!");
} function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("connection is not start.");
}
}
</script>
<form onsubmit="return false;">
<h3>WebSocket ChatRoom:</h3>
<textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
<br>
<input type="text" name="message" style="width: 300px" value="">
<input type="button" value="Send Message" onclick="send(this.form.message.value)">
<input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="Clear message">
</form>
<br>
<br>
</body>
</html>
然后启动ChatServer(非加密方式),最后在浏览器中访问localhost:8080(可打开多个窗口,多个客户端),其运行效果如下。


可以看到两个客户端之间可以正常进行通信,互相发送消息。
三、总结
本篇博文通过一个示例讲解了WebSocket协议的具体使用,可完成不同客户端之间的通信,也谢谢各位园友的观看~
【Netty】WebSocket的更多相关文章
- 【Netty】源码分析目录
前言 为方便系统的学习Netty,特整理文章目录如下. [Netty]第一个Netty应用 [Netty]Netty核心组件介绍 [Netty]Netty传输 [Netty]Netty之ByteBuf ...
- 【Netty】(7)---搭建websocket服务器
[Netty](7)---搭建websocket服务器 说明:本篇博客是基于学习某网有关视频教学. 目的:创建一个websocket服务器,获取客户端传来的数据,同时向客户端发送数据 一.服务端 1. ...
- 【Netty】(8)---理解ChannelPipeline
ChannelPipeline ChannelPipeline不是单独存在,它肯定会和Channel.ChannelHandler.ChannelHandlerContext关联在一起,所以有关概念这 ...
- 【Netty】(6) ---源码ServerBootstrap
[Netty]6 ---源码ServerBootstrap 之前写了两篇与Bootstrap相关的文章,一篇是ServerBootstrap的父类,一篇是客户端Bootstrap类,博客地址: [Ne ...
- 【Netty】(5)源码 Bootstrap
[Netty]5 源码 Bootstrap 上一篇讲了AbstractBootstrap,为这篇做了个铺垫. 一.概述 Bootstrap 是 Netty 提供的一个便利的工厂类, 我们可以通过它来完 ...
- 【Netty】netty学习之nio了解
[一]五种IO模型: (1)阻塞IO(2)非阻塞IO(任务提交,工作线程处理,委托线程等待工作线程处理结果的同时,也可以做其他的事情)(3)IO复用模型.(委托线程接收多个任务,将任务提交给工作线程. ...
- 【转】WebSocket 是什么原理?为什么可以实现持久连接?
WebSocket是HTML5出的东西 也就是说HTTP协议没有变化 但HTTP是不支持持久连接的(长连接,循环连接的不算)或者说WebSocket干脆就不是基于HTTP来执行的.但是...说不通啊. ...
- 【Netty】netty学习之nio网络编程的模型
[一]NIO服务器编程结构 [二]Netty3.x服务端线程模型
- 【Netty】Netty入门之WebSocket小例子
服务端: 引入Netty依赖 <!-- netty --> <dependency> <groupId>io.netty</groupId> <a ...
随机推荐
- 通过一个小游戏开始接触Python!
之前就一直嚷嚷着要找视频看学习Python,可是一直拖到今晚才开始....好好加油吧骚年,坚持不一定就能有好的结果,但是不坚持就一定是不好的!! 看着视频学习1: 首先,打开IDLE,在IDLE中新建 ...
- VC++内置数据类型存储及取值范围
亲测,基于win7 32位,vs2012编译 结果: 代码: #include "stdafx.h" #include <iostream> #include < ...
- iOS开发 - Swift使用JavaScriptCore与JS交互
一.前言 在这个提倡敏捷开发和H5横行的年代,原生App内嵌入一些H5页面已经成为一种流行的趋势.一套H5页面就可以适配复杂的iOS和Android页面,大量节省了开发和维护时间,如果本来就有移动端网 ...
- Python中使用with语句同时打开多个文件
下午小伙伴问了一个有趣的问题, 怎么用 Python 的 with 语句同时打开多个文件? 首先, Python 本身是支持同时在 with 中打开多个文件的 with open('a.txt', ' ...
- 【WPF】学习笔记(二)——依旧是一个电子签名板
这篇博客呢,主要谈谈在实现电子签名功能中踩过的几个坑:1.System.BadImageFormatException异常:2.无法加载DLL“###.dll”,: 找不到指定的模块. (异常来自 H ...
- Fish Shell
今天看到阮一峰同学的一篇博客(Fish shell 入门教程),讲述的非常详细.清楚,有兴趣的可以直接转去查看此文,本文仅提供一下个人使用心得. 一.fish shell 想必接触过类unix(包括w ...
- 在 ubuntu 下优雅的使用 Sublime Text 3 写 Python
此文章非技术文,就是一些对于 Sublime 俺之前经常用的 方法(快捷键 )和 工具 有一些工具俺也用过,但是效果不太好,可以说跟shi 一样,可能每个人的用处不一样,咱就不提了,免得招 来口舌之争 ...
- js,jQuery和DOM操作的总结(一)
废话不说,直接上图 一 js的基本操作 (1)js 的六种数据类型 var n4;//六种数据类型用typeof来确定类型,Null类型的用typeof是不行的,这个是特殊 alert(typeof ...
- 使用java API操作HDFS-相关环境的设置
用于装在编译类,即为hadoop的类路径 退出后重新登录,再使用env检查. jps可以直接使用了,表示已经设置成功. 在myclass之中创建类文件,这个myclass目录是自己创建的.
- 拖拽系列一、JavaScript实现简单的拖拽效果
前端拖拽相关应用汇总 在现实生活中就像男孩子牵着(拖着)女朋友的手穿过马路:从马路的一端走到另一端这种场景很常见: 而在前端开发中拖拽效果也算是前端开发中应用最常见.最普遍的特效:其拖拽涉及知 ...