Re: Zero Byte Terminated Strings
PurpleServerMonkey wrote:
Hi,
I'm writting a simple UDP server in Java, it's designed to take an
initial request packet from a C based client and perform further
actions. The networking side of things is fine however I'm having
problems dealing with a zero byte terminated string being sent from
the client.
Code Snippet:
byte[] data = new byte[1000];
DatagramSocket serverSocket = new DatagramSocket(1025);
DatagramPacket packet = new DatagramPacket(data, data.length);
serverSocket.receive(packet);
The recieved packet then gets put onto a queue for pickup by a thread
pool. It's in the threadpool that I look at processing the packet and
extracting the string information (represents a filename, mode, etc).
Note that the strings in this packet are zero byte terminated.
Code Snippet:
byte[] payload = new byte[1000];
payload = packet.getData();
What I'd like to know is, what is the best way to retrive zero byte
terminated strings from the byte array?
Thanks in advance for your assistance.
Actually very easy to do. Just create a String from your byte[] buffer
and split it on the 0s.
public class test {
public static void main (String[] args) throws Exception {
byte[] buf = { 0x54, 0x48, 0x49, 0x53, 0x00, 0x49, 0x53, 0x00,
0x41, 0x00, 0x54, 0x45, 0x53, 0x54, 0x00 };
String str = new String(buf);
String[] arr = str.split("\u0000");
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
}
--
Knute Johnson
email s/nospam/knute/