查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package org.jboss.netty.handler.codec.spdy;
17  
18  import org.jboss.netty.channel.ChannelHandlerContext;
19  import org.jboss.netty.channel.MessageEvent;
20  import org.jboss.netty.channel.SimpleChannelHandler;
21  import org.jboss.netty.handler.codec.http.HttpMessage;
22  import org.jboss.netty.handler.codec.http.HttpResponse;
23  
24  import java.util.Queue;
25  import java.util.concurrent.ConcurrentLinkedQueue;
26  
27  /**
28   * {@link SimpleChannelHandler} that takes care of adding the right streamId to the
29   * {@link HttpResponse} if one is not present. This makes it possible to just re-use plan handlers current used
30   * for HTTP.
31   */
32  public class SpdyHttpResponseStreamIdHandler extends SimpleChannelHandler {
33      private static final Integer NO_ID = -1;
34      private final Queue<Integer> ids = new ConcurrentLinkedQueue<Integer>();
35  
36      @Override
37      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
38          if (e.getMessage() instanceof HttpMessage) {
39              boolean contains = ((HttpMessage) e.getMessage()).headers().contains(SpdyHttpHeaders.Names.STREAM_ID);
40              if (!contains) {
41                  ids.add(NO_ID);
42              } else {
43                  ids.add(SpdyHttpHeaders.getStreamId((HttpMessage) e.getMessage()));
44              }
45          } else if (e.getMessage() instanceof SpdyRstStreamFrame) {
46              // remove id from the queue
47              ids.remove(((SpdyRstStreamFrame) e.getMessage()).getStreamId());
48          }
49          super.messageReceived(ctx, e);
50      }
51  
52      @Override
53      public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
54          if (e.getMessage() instanceof HttpResponse) {
55              HttpResponse response = (HttpResponse) e.getMessage();
56              Integer id = ids.poll();
57              if (id != null && id.intValue() != NO_ID && !response.headers().contains(SpdyHttpHeaders.Names.STREAM_ID)) {
58                  SpdyHttpHeaders.setStreamId(response, id);
59              }
60          }
61          super.writeRequested(ctx, e);
62      }
63  
64  }