全部 我會寫服務器的聊天室使用netty。併爲客戶端閃光。該協議使用帶有「\ r \ n」end的json字符串。我編寫了三個處理程序「MessageDecoder」,「MessageHandler」,「MessageEncoder」。並使用Flash客戶端發送消息。但我得到以下錯誤。如何使用netty聊天室。 flash客戶端
java.lang.IllegalStateException: decode() method must read at least one byte if it returned a frame (caused by: class com.mbaobao.chatroom.socket.handlers.MessageDecoder)
at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:294)
at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:216)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:274)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:261)
at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:351)
at org.jboss.netty.channel.socket.nio.NioWorker.processSelectedKeys(NioWorker.java:282)
at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:202)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
MessageDecoder
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
throws Exception {
logger.debug("message decode");
if (buffer.readableBytes() < 4) {
return null;
}
StringBuffer stringBuffer = new StringBuffer();
String json = null;
for (int i = 0; i < buffer.capacity(); i++) {
char c = (char) buffer.getByte(i);
logger.info(c);
stringBuffer.append(c);
if (c == 13 || c == 10) {
json = stringBuffer.toString();
break;
}
}
ChatData chatData = JSON.parseObject(json, ChatData.class);
return chatData;
}
我從來不寫套接字程序。只知道使用多線程管理套接字。但我認爲這太可怕了。所以我使用netty。但我不知道如何將它用於聊天室。
有人可以給我推薦嗎?
請提供MessageDecoder類的完整源代碼。 – Vincent 2012-04-01 01:20:50