Error sending JSON by Socket

3

When the JSON String is too large, there is a loss of part of the String in the submission. I'm sending it like this:

private void btComunicarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        List<PessoaMOD> pessoas = new ArrayList<PessoaMOD>();

        for (int i = 1; i <= 2000; i++) {
            pessoas.add(new PessoaMOD(i, "Pessoa " + i));
        }

        try {
            Socket cliente = new Socket("127.0.0.1", 12345);
            enviarMensagem(codificarListarDiretorio(pessoas), cliente);
        } catch (Exception e) {
            System.out.println("Erro: " + e.getMessage());
        } finally {
        }
    }  

public ByteArrayOutputStream codificarListarDiretorio(List<PessoaMOD> pessoas) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        Gson gson = new GsonBuilder().create();
        dos.write(gson.toJson(pessoas).getBytes());
        return bos;
    }

public void enviarMensagem(ByteArrayOutputStream mensagem, Socket socket) throws IOException {
        byte[] msg = mensagem.toByteArray();
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        out.writeInt(msg.length); //O tamanho da mensagem
        out.write(msg); //Os dados
        out.flush();
    }

And I get on the server like this:

int tamanhoMsg = entrada.readInt();                   
byte[] bufferJson = new byte[tamanhoMsg];
entrada.read(bufferJson, 0, bufferJson.length);
String json = new String(bufferJson);

Only the Json String does not come complete when it is too large.

What happens is that the number of bytes is greater than lenght supports, so the message size does not send complete.

I also tried to send by writeUTF () method,

But because the String is large, it generates this error: encoded string too long: 677789 bytes

    
asked by anonymous 23.02.2016 / 19:49

1 answer

1

Attempts to change the portion of the JSON reading in your code on the server from DataInputStream to BufferedReader :

// ...
long tamanhoMsg = entrada.readLong();

BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            // guava library - limita a leitura de um input stream
            ByteStreams.limit(        
                inputStream,                // input stream do socket
                tamanhoMsg                  // tamanho máximo a ser lido do input stream
            ),
        )
    );

JsonObject data = JsonParser.parse(reader)  // le o reader convertendo para  json
        getAsJsonObject();                  // retorna como JsonObject

// ...

You could also change the message size information from int to long.

    
24.02.2016 / 03:10