1、server端实现
源码实现:
public void run(int port){
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
ChannelPipeline pipeline = sc.pipeline();
// 服务端,对请求解码
pipeline.addLast("http-codec", new HttpServerCodec());
// 聚合器,把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
// 块写入处理器
pipeline.addLast("http-chunked",new ChunkedWriteHandler());
//自定义处理器
pipeline.addLast("handler", new WebSocketServerHandler());
}
});
ChannelFuture cf = b.bind(port).sync();
System.out.println("Web socket server started at port " + port + '.');
System.out.println("Open your browser and navigate to http://localhost:" + port + '/');
cf.channel().closeFuture().sync();
}catch(Exception e){
e.printStackTrace();
}finally{
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
- HttpServerCodec:将请求和应答消息解码为HTTP消息
- HttpObjectAggregator:将HTTP消息的多个部分合成一条完整的HTTP消息
- ChunkedWriteHandler:向客户端发送HTML5文件
2、WebsocketHandler实现
源码实现:
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
private static final Logger logger = Logger.getLogger(WebSocketServerHandler.class.getName());
private WebSocketServerHandshaker handshaker;
@Override
protected void messageReceived(ChannelHandlerContext ctx, Object obj)
throws Exception {
// 传统的HTTP接入
if(obj instanceof FullHttpRequest){
handleHttpRequest(ctx,(FullHttpRequest)obj);
}
// WebSocket接入
else if(obj instanceof WebSocketFrame){
handleWebSocketFrame(ctx,(WebSocketFrame)obj);
}
}
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception{
System.out.println("handleHttpRequest");
// 如果HTTP解码失败,返回HHTP异常
if(!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))){
sendHttpResponse(ctx,req,new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
}
// 构造握手响应返回,本机测试
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:8080/websocket", null, false);
handshaker =wsFactory.newHandshaker(req);
if(handshaker==null){
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
}else{
handshaker.handshake(ctx.channel(), req);
}
}
private void handleWebSocketFrame(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 TextWebSocketFrame)){
throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
}
// 返回应答消息
String request = ((TextWebSocketFrame)frame).text();
if(logger.isLoggable(Level.FINE)){
logger.fine(String.format("%s received %s", ctx.channel(), request));
}
ctx.channel().write(new TextWebSocketFrame(request+ " , 欢迎使用Netty WebSocket服务,现在时刻:"+ new java.util.Date().toString()));
}
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res){
// 返回应答给客户端
if(res.status().code() !=200){
ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
res.content().writeBytes(buf);
buf.release();
try {
Http2Headers http2Headers = HttpUtil.toHttp2Headers(res);
http2Headers.addLong(HttpHeaderNames.CONTENT_LENGTH, res.content().readableBytes());
}catch (Exception e){
e.printStackTrace();
}
}
// 如果是非Keep-Alive,关闭连接
ChannelFuture cf = ctx.channel().writeAndFlush(res);
try {
Http2Headers http2Headers = HttpUtil.toHttp2Headers(res);
Boolean keepAlive = Boolean.valueOf(http2Headers.get(HttpHeaderNames.CONTENT_LENGTH).toString());
if(!keepAlive || res.status().code() != 200){
cf.addListener(ChannelFutureListener.CLOSE);
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
链路建立成功之前:
- 第一次握手由HTTP协议承载,所以是一个HTTP消息,根据消息头中是否包含"Upgrade"字段来判断是否是websocket。
- 通过校验后,构造WebSocketServerHandshaker,通过它构造握手响应信息返回给客户端,同时将WebSocket相关的编码和解码类动态添加到ChannelPipeline中。
链路建立成功之后:
- 客户端通过文本框提交请求给服务端,Handler收到之后已经解码之后的WebSocketFrame消息。
- 如果是关闭按链路的指令就关闭链路
- 如果是维持链路的ping消息就返回Pong消息。
- 否则就返回应答消息
3、测试结果
websocket测试工具:
http://coolaf.com/tool/chattest,在浏览器中输以上网址,可以看到如下界面:
服务端输出如下:
客户端发送数据结果如下: