1 pom文件
本文的例子基于netty4.0。
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.24.Final</version>
</dependency>
2 服务端开发
websocket服务端的功能如下:服务端对请求的消息进行判断,如果第一次请求为http请求,进行握手连接;如果为合法的websocket,获取请求的消息文本,在其前面追加字符串”服务器收到并返回:“。
2.1 WebSocketServer启动类
public class WebSocketServer {
private final EventLoopGroup workerGroup = new NioEventLoopGroup();
private final EventLoopGroup bossGroup = new NioEventLoopGroup();
public void run(){
ServerBootstrap boot = new ServerBootstrap();
boot.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("http-codec",new HttpServerCodec());
pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
pipeline.addLast("http-chunked",new ChunkedWriteHandler());
pipeline.addLast("handler",new WebSocketServerHandler());
}
});
try {
Channel ch = boot.bind(2048).sync().channel();
System.out.println("websocket server start at port:2048");
ch.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new WebSocketServer().run();
}
}
备注:本例中默认的开通的端口为2048,可以自动动态配置
分析:
pipeline.addLast("http-codec",new HttpServerCodec());
上述代码表示将请求和应答的消息编码或者解码为HTTP消息;
pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
上述代码表示将HTTP消息的多个部分组合成一条完整的HTTP消息;
pipeline.addLast("http-chunked",new ChunkedWriteHandler());
上述代码表示向客户端发送HTML5文件,主要用于支持浏览器和服务端进行websocket通信;
pipeline.addLast("handler",new WebSocketServerHandler());
表示增加消息的Handler处理类WebSocketServerHandler。
2.2 WebSocket服务端处理类
在服务端处理类中需要处理两种类型的消息,一种的HTTP请求,一种是WebSocket请求;因为WebSocket在建立连接时需要HTTP协议的参与,所有第一次请求消息是由HTTP消息承载。
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>{
private WebSocketServerHandshaker handshaker;
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
throws Exception {
/**
* HTTP接入,WebSocket第一次连接使用HTTP连接,用于握手
*/
if(msg instanceof FullHttpRequest){
handleHttpRequest(ctx, (FullHttpRequest)msg);
}
/**
* Websocket 接入
*/
else if(msg instanceof WebSocketFrame){
handlerWebSocketFrame(ctx, (WebSocketFrame)msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
private void handleHttpRequest(ChannelHandlerContext ctx,FullHttpRequest req){
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:2048/ws", null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory
.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
private static void sendHttpResponse(ChannelHandlerContext ctx,
FullHttpRequest req, DefaultFullHttpResponse res) {
// 返回应答给客户端
if (res.getStatus().code() != 200) {
ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
CharsetUtil.UTF_8);
res.content().writeBytes(buf);
buf.release();
}
// 如果是非Keep-Alive,关闭连接
ChannelFuture f = ctx.channel().writeAndFlush(res);
if (!isKeepAlive(req) || res.getStatus().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
private static boolean isKeepAlive(FullHttpRequest req) {
return false;
}
private void handlerWebSocketFrame(ChannelHandlerContext ctx,
WebSocketFrame frame) {
/**
* 判断是否关闭链路的指令
*/
if (frame instanceof CloseWebSocketFrame) {
handshaker.close(ctx.channel(),
(CloseWebSocketFrame) frame.retain());
return;
}
/**
* 判断是否ping消息
*/
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(
new PongWebSocketFrame(frame.content().retain()));
return;
}
/**
* 本例程仅支持文本消息,不支持二进制消息
*/
if (frame instanceof BinaryWebSocketFrame) {
throw new UnsupportedOperationException(String.format(
"%s frame types not supported", frame.getClass().getName()));
}
if(frame instanceof TextWebSocketFrame){
// 返回应答消息
String request = ((TextWebSocketFrame) frame).text();
System.out.println("服务端收到:" + request);
ctx.channel().write(new TextWebSocketFrame("服务器收到并返回:"+request));
}
}
}
3 客户端页面
<head>
<title>Netty WebSocket DEMO</title>
</head>
<body>
<script type="text/javascript">
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:2048/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 + "连接被关闭";
};
} else {
alert("你的浏览器不支持!");
}
function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("连接没有开启.");
}
}
</script>
<form onsubmit="return false;">
<input type="text" name="message" value="Hello, World!"><input
type="button" value="发送消息"
onclick="send(this.form.message.value)">
<h3>输出:</h3>
<textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
<input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空">
</form>
</body>
</html>