我从客户端发送json:
while (!getMessages().isEmpty() && socket.isConnected()) {
Log.e("MQsize", getMessages().size() + "");
Message message = messageQueue.peek();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", MSG);
jsonObject.addProperty("token", user.getToken());
jsonObject.addProperty("to", message.getTo());
jsonObject.addProperty("body", message.getMessage());
sender.println(jsonObject.toString());
sender.flush();
messageQueue.poll();
}
结果我得到了字符串
{“ type”:“ TYPE”,“ token”:“ TOKEN”,“ to”:37,“ body”:“嘿!”}
我喜欢这个:
while (bytesRead != -1 && running) {
System.out.println("bytes read: " + bytesRead);
if (byteBuffer.position() > 2)
{
byteBuffer.flip();
byte[] lineBytes = new byte[bytesRead];
byteBuffer.get(lineBytes, 0, bytesRead);
String line = new String(lineBytes);
connectedSockets.add(ch);
parseMessage(ch, line, byteBuffer);
System.out.println("Message: " + line);
ch.write(ByteBuffer.wrap(line.getBytes()));
byteBuffer.clear();
}}
在服务器端,我解析了这个json并得到了相同的结果。 但是,有时,如果我向服务器发送多条消息,它将打印出正确的JSON,但在解析时显示“ JSONException no such JsonObject(“ type”)“。在此时,该字段为“类型”。当我推送“格式错误”的json时,它看起来像
{“来自”:37,“身体”:“嘿!”}令牌“,”至“:82,”身体“:”他
仅此而已。您看不到任何类型。发生了什么事?
我的解析函数:
JSONObject jsonObject = new JSONObject(clientMessage);
String type = jsonObject.getString("type");
if (type.equals(OPEN))
open(ch, clientMessage, byteBuffer);
if (type.equals(CLOSE))
close(ch, clientMessage, byteBuffer);
if (type.equals(MESSAGE))
message(ch, clientMessage, byteBuffer);