public class MyClass{
static final String BROADCAST = "Broadcasting";
public static final int PORT = 12344;
public static String host = "localhost";
public static void main(String[] args) {
// TODO Auto-generated method stub
DatagramSocket serverSocket;
try {
serverSocket = new DatagramSocket(PORT);
InetAddress addr = InetAddress.getByName(host);
byte[] sendData = BROADCAST.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, //data byte array
sendData.length, //number of bytes
addr, //destination host address
PORT); //destination port
serverSocket.send(sendPacket);
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(
rcvData, rcvData.length);
//packet gets filled in by receive
serverSocket.receive(rcvPacket);
//Why the two Strings are not the same?
//Why the bytes derived from the same string different?
byte[] a = rcvData;
byte[] b= BROADCAST.getBytes();
System.out.println(a.equals(b));
System.out.println(new String(a));
System.out.println(new String(b));
System.out.println((new String(a).equals(new String(b))));
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have noticed that
1) The byte arrays I got using getByte() method are different.
2) Even though the String of a and b(from the code) are exactly the same, but they are not equal.
Here is the output I get from four print statements:
false
Broadcasting
Broadcasting
false