3
I’m building a system to communicate via Socket:
The client system sends the following information:
1 - int - message size
2 - bytes - the message
The message consists of:
1 - int - code of the method I want to run on the server
2 - int - size of the list I want to send
3 - int - person id
4 - int - string size of person name
5 - String - person name string
Topics 3, 4 and 5 run for each item in the list
My client system gets like this:
private void btComunicarActionPerformed(java.awt.event.ActionEvent evt) {
List<PessoaMOD> pessoas = new ArrayList<PessoaMOD>();
pessoas.add(new PessoaMOD(1, "Pessoa 1"));
pessoas.add(new PessoaMOD(2, "Pessoa 2"));
pessoas.add(new PessoaMOD(3, "Pessoa 3"));
pessoas.add(new PessoaMOD(4, "Pessoa 4"));
pessoas.add(new PessoaMOD(5, "Pessoa 5"));
pessoas.add(new PessoaMOD(6, "Pessoa 6"));
pessoas.add(new PessoaMOD(7, "Pessoa 7"));
pessoas.add(new PessoaMOD(8, "Pessoa 8"));
try {
Socket cliente = new Socket("127.0.0.1", 12345);
enviarMensagem(codificarListarPessoas(pessoas), cliente);
} catch (Exception e) {
System.out.println("Erro: " + e.getMessage());
} finally {
}
}
public ByteArrayOutputStream codificarListarPessoas(List<PessoaMOD> pessoas) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeByte(1); //Método 1, gravar pessoas
dos.writeInt(pessoas.size()); // tamanho da lista
for (PessoaMOD p : pessoas) {
dos.writeInt(p.getId()); // id da pessoa
dos.writeInt(p.getNome().length()); //Nr de caracteres do nome da pessoa
dos.writeChars(p.getNome()); //Nome da pessoa
}
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();
}
My question is to read this on the server: I’m doing it like this on the server:
private void btIniciarActionPerformed(java.awt.event.ActionEvent evt) {
new Thread() {
@Override
public void run() {
try {
ServerSocket servidor = new ServerSocket(12345);
System.out.println("Servidor ouvindo a porta 12345");
while (true) {
Socket cliente = servidor.accept();
System.out.println("Cliente conectado: " + cliente.getInetAddress().getHostAddress());
DataInputStream entrada = new DataInputStream(cliente.getInputStream());
int tamanhoMsg = entrada.readInt(); // ler tamanho da mensagem
// leio os bytes de acordo com o
//tamanho da mensagem lida anteriormente
byte[] bytes = new byte[tamanhoMsg];
int op = entrada.read(bytes, 0 , bytes.length);
// Como posso fazer a leitura separada dos dados enviados?
entrada.close();
cliente.close();
}
} catch (Exception e) {
System.out.println("Erro: " + e.getMessage());
} finally {
}
}
}.start();
}
I read the message size and received all bytes according to the size sent.....
But now how can I separate these bytes according to the data I sent, ie separate list size, id, string size, string name.
I believe you need more information about, for example, number size and String encoding.
– Pablo Almeida
So, what would be this "size of the numbers"? How can I dismember this my bytes?
– Rodrigo Lima
In the other answer you said that you yourself are sending this data on the other side. In this case, why are you using raw binary data? Why not use serialization?
– Pablo Almeida
To use serialization I would have to use Objectinputstream and Objectoutputstream, and read in several tutorials that it is not recommended to use these classes nor send by serialization. And by sending an object, for example, a Personal List>, the name of the packages in the Personal classmod would have to be the same in the client and server application. i thought to convert my object to JSON and send as String, and on the other side do the reverse process, will it be feasible?
– Rodrigo Lima
You need to understand the arguments used by those who spoke that you should not use Objectoutputstream instead of blindly following. If there are issues even that may affect your application, you can still choose to transfer your data using a common data representation such as JSON or XML. It will make your life a lot easier, especially when it comes to badly formatted data.
– Pablo Almeida
Got, if I send as JSON the transmission does not get slow? Or if the String is too large, there can be no data loss?
– Rodrigo Lima
"Premature optimization is the root of all evils" :) Worry first about writing the cleanest and simplest code that solves your problem. If there is slowness, measure and verify what is the cause.
– Pablo Almeida
Ok, but as I said, if the JSON String is too large, no data loss can occur?
– Rodrigo Lima
Network protocols ensure that this will not occur without warning. If it does, you will receive an error that you can handle. But I don’t think this data will get too big anyway.
– Pablo Almeida
I’ll take a test with a big load of a comic book, anything I come back here. VLW
– Rodrigo Lima
I edited the topic, there is loss of String with large JSON.
– Rodrigo Lima
Okay. Can you open up a new question and put that content there? This way you will get more attention and will not distort the purpose of this, making this and the other more useful for other users as well.
– Pablo Almeida
I created it. VLW for help.
– Rodrigo Lima