[英]Server sending a greeting message with websocket and netty -> causing exception
我有一個使用Netty(4.0.17)的websocket服務器來回答來自JavaScript客戶端的請求。 通信工作正常,但當我嘗試在客戶端連接時立即發送問候消息時,我有一個例外。
我的代碼看起來像這樣:
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
我想這可能是因為一旦建立連接但在websocket握手完成之前, channelActive()
就會被調用。 我如何等待握手完成然后發送問候消息(客戶端尚未發送任何請求)?
有關信息,我的初始化是:
@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);
只是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"));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.