I need to read from an ip/port, through UDP and I can't. From an external utility, I see that the reader (RFID) reads correctly from said port/ip through UDP. Now, I want to read it from java and I can't (I clarify that it is the first time that I am going to read from a port/ip through java). My code is the following, I hope you can guide me:
package test_rfid_udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Test_RFID_UDP {
public static void main(String args[]) {
try {
int port = 2000;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket();
// Create a buffer to read datagrams into. If a
// packet is larger than this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[2048];
// Create a packet to receive data into the buffer
InetAddress address = InetAddress.getByName("192.168.0.77");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 2000);
// Now loop forever, waiting to receive packets and printing them.
while (true) {
// Wait to receive a datagram
dsocket.receive(packet);
// Convert the contents to a string, and display them
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
I also attach an image of the readings made with the utility. I hope you can help me.
Thank you
I have been looking at the documentation of the Java API for UDP and the truth is that it is not very intuitive:
What you want is to receive, so I think you don't have to specify the port or IP there:
And to listen to the port, it would be something like
I haven't been able to test this code, but I think you have to somehow let the sender know that you're expecting packets from them, and that's (I think) what the method does
connect