Skip to content

Java 7+ UDP broadcast/unicast/multicast sender/receiver(server)

License

Notifications You must be signed in to change notification settings

miktim/UdpSocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

# UdpSocket, MIT (c) 2019,2021 [email protected]
Java SE 7+ UDP broadcast/unicast/multicast sender/receiver

Release notes:
  - don't forget to open the required UDP port in your firewall;
  - the socket type (datagram/multicast) is determined by the requested address (inetAddr);
  - the created socket is bound to the port and specified bind address (bindAddr);
  - multicast sockets are created with loopback disabled and one hop;
  - the datagram socket connects to a non-broadcast, not anyLocal address;
  - only non-multicast IPv4 addresses ending in .255 are considered broadcast;
  - DO NOT disable datagram socket timeout.

package org.miktim.udpsocket;

Overview:

  Class UdpSocket extends Thread;
    Constructors:
      UdpSocket(int port) throws IOException; // broadcast datagram socket (255.255.255.255)
      UdpSocket(int port, InetAddress inetAddr) throws IOException;
      UdpSocket(int port, InetAddress inetAddr, InetAddress bindAddr) throws IOException;

    Methods:
      static void setReuseAddress(boolean on); // enabled by default
      static boolean getReuseAddress();
      static void send(byte[] buf, InetAddress addr, int port); // send datagram
      
      void send(byte[] buf) throws IOException; // send using socket
      void send(byte[] buf, InetAddress addr) throws IOException; // send using socket
      void send(byte[] buf, int port, InetAddress addr) throws IOException; // send using socket

      void setBufLength(int len); // set the buffer length of the receiving datagram packets
      int getBufLength();
      void receive(UdpSocket.Handler handler); // start receiving datagrams

      void close(); // stop receiving, close datagram socket
      boolean isOpen(); 
      boolean isReceiving();
      boolean isMulticast();
      boolean isBroadcast();
      InetAddress getInetAddress(); // returns inetAddr parameter
      DatagramSocket getDatagramSocket();

    Interface UdpSocket.Handler:
      void onStart(UdpSocket socket);
      void onPacket(UdpSocket socket, DatagramPacket packet);
      void onError(UdpSocket socket, Exception e);
      void onClose(UdpSocket socket); // called BEFORE closing the datagram socket

About

Java 7+ UDP broadcast/unicast/multicast sender/receiver(server)

Topics

Resources

License

Stars

Watchers

Forks

Packages