user2268507
user2268507

Reputation:

Sending Message via DatagramChannel

I am sending a message via a DatagramChannel as follows:

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
String request_message = "request";
buf.put(request_message.getBytes());
buf.flip();

int bytesSent = udpserver.send(buf, successor_port_1); // udpserver is a DatagramChannel

I then read the message on the server:

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();

String message = new String(buf.array(), Charset.forName("UTF-8"));
System.out.println(message); //print message for testing purposes

if (message == "request"){
    //code here does not get executed
 }

The problem is, my code doesn't enter the "if" statement even though message = "request" which also seems to be confirmed by my print statement.

Any help would be appreciated!

Upvotes: 0

Views: 342

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61148

The reason for this is that Strings in java need to be compared with .equals, so your test should be:

if (message.equals("request")){

This is because, in Java, == tests whether two object are the same instance (it tests reference equality - do both the references point to the same memory) rather than equal.

You can carry out a quick test:

System.out.println("request" == new String("request"));

Output:

false

For more information read this SO answer.

Upvotes: 1

Related Questions