Netty小記——web socket分片聚合實現

在netty中已經對web socket的分片重組進行了相應的實現,具體的實現類是 WebSocketFrameAggregator,該類繼承自netty的消息聚合器MessageAggregator。

MessageAggregator

 ......

 * @param <I> the type that covers both start message and content message
 * @param <S> the type of the start message
 * @param <C> the type of the content message (must be a subtype of {@link ByteBufHolder})
 * @param <O> the type of the aggregated message (must be a subtype of {@code S} and {@link ByteBufHolder})
 */
public abstract class MessageAggregator<I, S, C extends ByteBufHolder, O extends ByteBufHolder>
......
 // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
CompositeByteBuf content = ctx.alloc().compositeBuffer(maxCumulationBufferComponents);
if (m instanceof ByteBufHolder) {
    appendPartialContent(content, ((ByteBufHolder) m).content());
 }
currentMessage = beginAggregation(m, content);

通過代碼可以看到,該消息聚合器主要是通過對消息進行分類進行聚合的,該消息聚合器是被掛在channel的pipeline上的,通過判斷傳給該聚合器handler的消息的類型是否是需要聚合的消息體來進行聚合,並通過isLastContentMessage判斷消息是否是最後一個分片來決定是否終止消息的聚合操作。

web socket自身的分片機制和netty提供的消息聚合器原理一致, 所以通過繼承該聚合器可以實現web socket自身的分片的效果。

此外針對消息內容較大的情況可以使用基於壓縮的web socket傳輸。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章