正确实现方法messageReceived()(Netty)

时间:2015-04-07 09:17:35

标签: java server netty

如何解决这种写作方法messageReceived() 更准确地说,如何根据连接客户端的消息内容配置服务器的响应。

String fromClientData ="";
String [] params;
User user;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws IOException {
    fromClientData = e.getMessage().toString();
    params = fromClientData.split(";");
    String idOrDemo = params[1];

    if (params[0].equals("demo")) {
        user = useService.getById(idOrDemo);
        e.getChannel().write("demo;" + user.getId() + ";");
    }

    if (params[0].equals("site")) {
        Integer id = Integer.parseInt(idOrDemo);
        user = userService2.getById(id);

        if (params[2].split(":")[0].equals("SOME")) {
            //todo something
        }

        ctx.getChannel().write("SOME:" + str + ";");    
    } else {

        user.setChannelUser(e.getChannel());
        if (params[1].equals("updateCache")) {
            sendUpdate();
        }
        else {
            setClient();
        }
    }
    } else {
        Integer id = Integer.parseInt(idOrDemo);
        user = userService.getById(id);

        user.setChannelUser(e.getChannel());
        if (params[1].equals("updateCache")) {
            sendUpdate();
        }
        else {
            setClient();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

首先,

之后
e.getChannel().write("demo;" + user.getId() + ";");

你需要做:

e.getChannel().flush()或替换为e.getChannel().writeAndFlush("demo;" + user.getId() + ";");

其次,在拆分后,我建议将if中的条件更改为:

if ("demo".equals(params[0])) { }

因为,如果params[0]为null,则会出现NullPointerException。