In the following code for sockets, I declare a byte buffer and listen for client messages in a loop:
// Create some buffer
byte[] buffer = new byte[512];
while (true)
{
// Listen for messages from Client
int length = socket.getInputStream().read(buffer);
if (length != -1)
System.out.println(new String(buffer));
else
break;
// Reset buffer here to zeros?
}
Each time I'd require to reset the contents of buffer to receive a new message. What's the proper way to do this?
You don't need to reset the buffer, you need to a String
constructor that does not go past the end of the part of the buffer that has the bytes received:
if (length != -1) {
System.out.println(new String(buffer, 0, length));
}
Now your code will work even if the buffer is dirty.
Note: For better portability pass the desired Charset
to String
constructor. Otherwise the String
you construct may not match the string that has been transmitted to you through the socket.
Agree with dasblinkenlight answers , but to answer the question itself (how to reset an array), you can use Arrays.fill
to set a value to every cell
byte[] array = new byte[10];
Arrays.fill(array, (byte)0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.