从ByteBuffer解析多个JSON

时间:2016-04-26 08:43:42

标签: java android sockets

我有纯粹而简单的Java Nio套接字服务器。使用JSON实现数据传输。 1 clien都工作正常,但当我尝试启动工作负载测试时 - 出现了一些问题。这是我解析传入的ByteBuffer的方法(MessageFromBuffer只是byte []的包装器):

private JSONObject parseIncomingMessageToJson(MessageFromBuffer messageFromBuffer) {
        int size = messageFromBuffer.getSize();
        byte[] data = messageFromBuffer.getData();

        byte[] dataCopy = new byte[size];
        System.arraycopy(data, 0, dataCopy, 0, size);

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonMessage = null;

        try {
            jsonMessage = (JSONObject) jsonParser.parse(new String(dataCopy));
        } catch (ParseException pe) {
            System.out.println("Error formatting incoming message to json:  " + new String(messageFromBuffer.getData()));
        }

        return jsonMessage;
    }

当缓冲区仅包含一个json实体时 - 一切正常。但是在100个客户端攻击期间,缓冲区可以填充多个json enities,如图所示(所有测试客户端发送相同的数据):

Error formatting incoming message to json:  {"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}
{"TYPE":"REGISTRATION","LOGIN":"Padre","PASSWORD":"3214"}

方法抛出异常并返回任何内容。每次从SOcketChanel读取后我清除缓冲区 - 所以这些消息都丢失了。在这种情况下是否有一些适当的JSON解析技术?

1 个答案:

答案 0 :(得分:2)

根据您发布的内容,它看起来类似于this,因为输出是使用下一行字符分隔的。您可以利用它将字符串拆分为序列化json响应数组。

然后你可以将它们分别解析为json对象。