1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
| package com.laowj.websocket.handler;
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger;
import static io.netty.handler.codec.http.HttpHeaderNames.HOST; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpUtil.isKeepAlive; import static io.netty.handler.codec.http.HttpUtil.setContentLength; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> { private static final Logger logger = Logger .getLogger(WebSocketServerHandler.class.getName());
private WebSocketServerHandshaker handshaker;
private static final String WEBSOCKET_PATH = "/ws_protocol";
public static Map<String, ChannelGroup> channelGroupMap = new ConcurrentHashMap<>();
private static final String HTTP_REQUEST_STRING = "token";
private static AttributeKey<String> TOKEN_CHANNEL_KEYS = AttributeKey.valueOf("TOKEN.CHANNEL.KEYS");
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } }
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; }
if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; }
if ("/favicon.ico".equals(req.uri()) || ("/".equals(req.uri()))) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); return; }
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri()); Map<String, List<String>> parameters = queryStringDecoder.parameters();
if (parameters.size() == 0 || !parameters.containsKey(HTTP_REQUEST_STRING)) { System.err.printf(HTTP_REQUEST_STRING + "参数不可缺省"); sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); return; }
String token = parameters.get(HTTP_REQUEST_STRING).get(0);
if (!channelGroupMap.containsKey(token)) { channelGroupMap.put(token, new DefaultChannelGroup(GlobalEventExecutor.INSTANCE)); } channelGroupMap.get(token).add(ctx.channel()); Attribute<String> tokenAttr = ctx.channel().attr(TOKEN_CHANNEL_KEYS); tokenAttr.setIfAbsent(token);
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), 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) throws Exception {
if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } 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 )); }
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(); setContentLength(res, res.content().readableBytes()); }
ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); close(ctx); }
private void close(ChannelHandlerContext ctx){ Attribute<String> tokenAttr = ctx.channel().attr(TOKEN_CHANNEL_KEYS); String token = tokenAttr.get(); if (token != null && channelGroupMap.containsKey(token)) { ChannelGroup channelGroup = channelGroupMap.get(token); int len = channelGroup.size(); if (len <= 1) { channelGroupMap.remove(token); }else{ channelGroupMap.get(token).remove(ctx.channel()); } } ctx.close(); }
@Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { close(ctx); }
private static String getWebSocketLocation(FullHttpRequest req) { String location = req.headers().get(HOST) + WEBSOCKET_PATH; return "ws://" + location; } }
|