Parse byte escape character

I am sending requests from a client socket to a server socket, and I want to delimit requests (send as a byte array) using an escape character ("\ n"). I want to have one request per new line Example:

"Request1 " "Request2" "Request3" 

To do this, I need to convert "\ n" to byte to compare queries like this

  byte[] request= new byte[1024]; int nextByte; while((nextByte=in.read(request))!=DELIMITER) { String chaine = new String( request,0,nextByte); System.out.println("Request send from server: " + chaine); } 

The problem is that I get an exception in numeric format when I try to convert "\ n" to byte

 private static final byte DELIMITER = Byte.valueOf("\n"); 

Thank you very much

+4
source share
4 answers

Try the following:

 private static final byte DELIMITER = (byte) '\n'; 

Double quotes are for string literals, single quotes for characters and bytes # valueOf does something else than what you think.

If you want to turn String into bytes, you must:

 byte[] theBytes = "\n".getBytes("UTF-8"); 
+7
source

There are many answers to your question, but the next question will be, why is my loop not working? for example, if you read exactly 10 bytes, it will stop, and if you send two messages at once, they will be read in one reading.

What you really want is something like

 BufferedReader br = new BufferedReader(new InputStreamReader(in)); for(String line; (line = br.readline()) != null; ) { System.out.println("Line read: " + line); } 
+2
source

Please, try

 private static final byte DELIMITER = '\n'; 

'\ n' is of type char , which corresponds to unsigned short. But keep in mind that short in Java is always signed.

+1
source

How about this:

 private static final byte DELIMITER = '\n'; 

Attaching a new line in single quotes makes a char value that can be assigned to a byte without losing information in this case.

+1
source

Source: https://habr.com/ru/post/1433791/


All Articles