com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 44021 path $.object
@Override protected void initChannel(SocketChannel c) throws Exception { ChannelPipeline pipeline = c.pipeline(); pipeline.addLast(new DelimiterBasedFrameDecoder(Server.MAX_FRAME_SIZE, Delimiters.lineDelimiter())); pipeline.addLast(new StringDecoder(Charset.forName("UTF-8"))); pipeline.addLast(new StringEncoder(Charset.forName("UTF-8")));
pipeline.addLast("handler", new ServerHandler(p2p)); }
private void sendMessage(ChannelHandlerContext ctx, Message msg, boolean closeConnection) { String msgJson = gson.toJson(msg) + "\r\n"; ChannelFuture future = ctx.writeAndFlush(msgJson); if (closeConnection) { future.addListener(ChannelFutureListener.CLOSE); } }
public Message sendRequestMessage(Message msg) throws Exception { Peer peer = getPeer();
Socket newClientSocket = new Socket(peer.getHost(), peer.getPort()); InputStream bounded = new BoundedInputStream(newClientSocket.getInputStream(), MAX_FRAME_SIZE); BufferedReader reader = new BufferedReader(new InputStreamReader(bounded)); PrintWriter writer = new PrintWriter(newClientSocket.getOutputStream());
//Send request Message writer.print(gson.toJson(msg, Message.class) + "\r\n"); writer.flush();
String response = reader.readLine(); try { newClientSocket.close(); } catch (Exception e) { logger.warn("Can't close socket: " + peer.toString(), e); }
Message responseMessage = gson.fromJson(response, Message.class); return responseMessage;
}
1. use netty in client side to make thing easier;
2. use JsonObjectDecoder in both server side and client side, don't use DelimiterBasedFrameDecoder;
3. don't add "\r\n" at the end of the json string at both server side and client side when sending to the peer.