Java - I can not read UDP socket from port / ip

2

I need to read from an ip / port, using UDP and I do not get it. From an external utility, I see that the reader (RFID) correctly reads from said port / ip through UDP. Now, I want to read it from java and I can not (I clarify that it is the first time that I will read from a port / ip using java). My code is this, 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.

Thanks

    
asked by Emiliano Torres 22.10.2018 в 16:31
source

1 answer

1

I have been looking at the Java API documentation for UDP and the truth is that it is not very intuitive:

DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
     

Constructs a datagram packet for sending packets of length length   with offset offset to the specified port number on the specified host.

You want to receive, so I think you do not have to specify the port or IP there:

  

DatagramPacket(byte[] buf, int length)   Constructs a DatagramPacket for receiving packets of length length .

And to hear the port, it would be something like

DatagramSocket dsocket = new DatagramSocket();
dsocket.connect(address,port);

I have not been able to test this code, but I think that somehow you have to let the sender know that you are waiting for his packages, and that is (I think) what the connect method does

    
answered by 22.10.2018 / 17:19
source