2014-03-01 35 views
3

我有一個websocket服務器使用Netty(4.0.17)來回應來自JavaScript客戶端的請求。 通信工作正常,但我嘗試在客戶端連接時立即發送問候消息時出現異常。服務器發送帶有websocket和netty的問候消息 - >導致異常

我的代碼看起來像這樣:

public class LiveOthelloWSHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { 

    @Override 
    public void channelActive(ChannelHandlerContext ctx) throws Exception { 
     super.channelActive(ctx); 
     ChannelFuture f = ctx.channel().writeAndFlush(new TextWebSocketFrame("(gameID=0)[LiveOthelloServer="+ VERSION_NUMBER + "]\n")); 
    } 

// ... 

    @Override 
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception { 

     final String request = frame.text(); 
     Channel thisChannel = ctx.channel(); 

     // Do something with request 
     // Write back 

     thisChannel.writeAndFlush(new TextWebSocketFrame(response + "\n")); 
    } 
} 

channelRead0()是確定的,客戶端發送消息和服務器的答案回,沒有任何問題。 什麼不起作用是「問候」部分。我想發送歡迎信息給客戶端(在ChannelActive()方法使用VERSION_NUMBER字符串),但我總是得到一個異常:

java.lang.UnsupportedOperationException: unsupported message type: TextWebSocketFrame 

我想這也許是因爲channelActive(),即會調用作爲連接是在websocket握手完成之前建立的。如何等待握手完成,然後發送問候消息(客戶端尚未發送任何請求)?

的信息,我的初始化:

@Override 
public void initChannel(SocketChannel ch) throws Exception { 
    ChannelPipeline pipeline = ch.pipeline(); 
    pipeline.addLast(
        new HttpRequestDecoder(), 
        new HttpObjectAggregator(65536), 
        new HttpResponseEncoder(), 
        new WebSocketServerProtocolHandler("/websocket"), 
        myLiveOthelloWSHandler); 

回答

3

只是RTFM ...檢測握手

http://netty.io/4.0/api/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.html

最好的辦法是重寫ChannelInboundHandler.userEventTriggered ... 所以我不得不加:

@Override 
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 
    super.userEventTriggered(ctx, evt); 
    if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { 
     ChannelFuture f = ctx.channel().writeAndFlush(new TextWebSocketFrame("(gameID=0)[LiveOthelloServer="+ VERSION_NUMBER + "]\n")); 
    } 
}