Skip to main content

Broadcast data using UDP in Java Socket Programming

If we want client to automatically discover server IP,we can do this by broadcasting a data packet with some identifier to the server , server extracts the client IP and then server send some identifier to the client ,client then extracts the IP from the packet received from the server.Here are simple work flows that is similar to DHCP protocol:-

On the server side:-
1.) Open a socket on the server that listens to the UDP request.
2.) Make a loop that handles the UDP request and responses.
3.) Inside the loop,check the received UDP packed to see if its valid by identifier.
4.) Still inside the loop , send a response to the IP and port of the received packet.

On the client side:-
1.) Open a socket on a random port.
2.) Loop over the computer network interfaces and get their broadcast address.
3.) send the UDP Packet inside the loop to the interface's broadcast address.
4.) wait for a reply
5.) when we have a reply , check to see if the package is valid.
6.) When its valid, get the package sender IP address ;this is the server's IP address
7.) Close the socket.

Here are the basic application that sends an array from client side to the server , server sorts the array and reply back to client.Client broadcast UDP packet to the server,client extracts server IP and then send array to the server.

Here are the client side JAVA code:-
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.Enumeration;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Color;
public class Client extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel lblConnection;
private JLabel lblResult ;
    private int port;
    private JTextField textField_1;
    private JTextField textField_2;
    private Socket client;
    private DataOutputStream out;
    private DatagramSocket c=null;
    private InetAddress ip=null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {

Client frame = new Client();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Client() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
try {
if(client!=null){
client.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setTitle("UDP Client");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setBackground(new Color(112,128,144));
setContentPane(contentPane);
setVisible(true);
contentPane.setLayout(null);

JLabel lblSortArrayUsing = new JLabel("Sort Array using remote server");
lblSortArrayUsing.setFont(new Font("Dialog", Font.BOLD, 14));
lblSortArrayUsing.setBounds(98, 0, 256, 28);
contentPane.add(lblSortArrayUsing);

JLabel lblEnterArray = new JLabel("Enter Array(space seperated):");
lblEnterArray.setBounds(71, 126, 263, 15);
contentPane.add(lblEnterArray);

textField = new JTextField();
textField.setBounds(71, 153, 253, 19);
contentPane.add(textField);
textField.setColumns(10);

lblResult = new JLabel("Result:");
lblResult.setBounds(29, 212, 70, 15);
contentPane.add(lblResult);

lblResult = new JLabel("");
lblResult.setBounds(98, 200, 338, 28);
contentPane.add(lblResult);


JButton btnNewButton = new JButton("Go");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String s=textField.getText();
if(s=="" || s.equalsIgnoreCase("")){
JOptionPane.showMessageDialog(contentPane, "Please Enter Array Values");
}else{
sendData(ip);        
}
}
});
btnNewButton.setBounds(351, 150, 70, 25);
contentPane.add(btnNewButton);

lblConnection = new JLabel("");
lblConnection.setForeground(Color.GREEN);
lblConnection.setBounds(108, 36, 280, 15);
contentPane.add(lblConnection);

JLabel lblIpAddress = new JLabel("Ip Address:");
lblIpAddress.setBounds(12, 75, 93, 28);
contentPane.add(lblIpAddress);

textField_1 = new JTextField();
textField_1.setBounds(98, 80, 114, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);

JLabel lblPort = new JLabel("Port:");
lblPort.setBounds(230, 82, 51, 15);
contentPane.add(lblPort);

textField_2 = new JTextField();
textField_2.setBounds(273, 80, 64, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);

lblConnection.setText("waiting for connection");
ip=sendDiscoveryPacket();
if(ip!=null){
String str="Just connected to "+ip.getHostAddress();
        lblConnection.setText(str);
        textField_1.setText(ip.getHostAddress());
        textField_2.setText("9876");
}else{
String str="waiting for connection to server";
        lblConnection.setText(str);
}

}
//send the discovery packet across the network to know the IP of server.
public InetAddress sendDiscoveryPacket(){
InetAddress ip=null;
try{
 c = new DatagramSocket();
 c.setBroadcast(true);
 byte[] sendDataIdentifier = "DISCOVERSERVER".getBytes();
   Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
   while (interfaces.hasMoreElements()) {
    NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();
    System.out.println("Network interface===>"+networkInterface.getDisplayName());
    if (networkInterface.isLoopback()) {
    continue;
    }
    for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
    InetAddress broadcast = interfaceAddress.getBroadcast();
    if (broadcast == null) {
    continue;
    }
    try {
    DatagramPacket sendPacket = new                    DatagramPacket(sendDataIdentifier, sendDataIdentifier.length, broadcast, 9876);
    c.send(sendPacket);
    } catch (Exception e) {
    }
    System.out.println(">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
    }
   }
   System.out.println(">>> Done looping over all network interfaces. Now waiting for a reply!");
     byte[] recvBuf = new byte[15000];
     DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
     c.receive(receivePacket);
   
       System.out.println(">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress());
     
         String message = new String(receivePacket.getData()).trim();
   
         if (message.equals("Ackwnoledged")) {
         ip=receivePacket.getAddress();
         }
          c.close();
} catch (IOException ex) {

}
return ip;
}

//Method to send and receive data to/from server
public void sendData(InetAddress ip){
String arr=textField.getText();
String arr1[]=arr.trim().split(" ");
arr=arr1.length+" "+arr.trim();
System.out.println("Data ==>"+arr);
byte b[]=arr.getBytes();
try {
c = new DatagramSocket();
DatagramPacket sendPacket = new DatagramPacket(b, b.length,ip , 9876);
c.send(sendPacket);
System.out.println("send to server IP:"+ip.getHostAddress());
//receive data
byte[] recvBuf = new byte[15000];
     DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
     c.receive(receivePacket);
     String message = new String(receivePacket.getData()).trim();
System.out.println("rece data====>"+message);
lblResult.setText(message);
} catch (Exception e) {
}
}
}

Here are the server side Java code:-
import java.net.*;
public class Server extends Thread
{
public static void main(String[] args) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876,InetAddress.getByName("0.0.0.0"));
serverSocket.setBroadcast(true);
DatagramPacket recievePacket = null;
while(true)
{

byte[] recieveData = new byte[1024];
byte[] recieveArray = new byte[1024];
byte[] sendData = new byte[1024];
byte[] sendArray = new byte[1024];
try
{
recievePacket = new DatagramPacket(recieveData, recieveData.length);
serverSocket.receive(recievePacket);
InetAddress IPAddress = recievePacket.getAddress();
System.out.println("Packet Received from : "+IPAddress.getHostAddress());
int port = recievePacket.getPort();

String s = new String(recievePacket.getData());
if("DISCOVERSERVER".equalsIgnoreCase(s.trim()))
{
sendData = "Ackwnoledged".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,port);
serverSocket.send(sendPacket);

recievePacket = new DatagramPacket(recieveArray, recieveArray.length);

serverSocket.receive(recievePacket);
port = recievePacket.getPort();

String s2 = new String(recievePacket.getData());

String s1[] = (s2.trim()).split("\\s+");

int n = Integer.parseInt(s1[0]);
int arr[] = new int[n];
for(int i=0;i<s1.length-1;i++)
{
arr[i] = Integer.parseInt(s1[i+1]);
}
System.out.println("Array received");
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(arr[i]<arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
StringBuffer ans = new StringBuffer();

for(int i=0;i<n-1;i++)
{
ans = ans.append(arr[i]);
ans = ans.append(" ");
}
ans=ans.append(arr[n-1]);
System.out.println("Array sorted");
sendArray = ans.toString().getBytes();
sendPacket = new DatagramPacket(sendArray, sendArray.length, IPAddress,port);
serverSocket.send(sendPacket);
System.out.println("Data Sent");
}
}
catch(Exception e)
{
e.printStackTrace();
break;
}
}
}
}

Comments

Popular posts from this blog

Long-Polling vs WebSockets vs Server-Sent Events

Long-Polling vs WebSockets vs Server-Sent Events  Long-Polling, WebSockets, and Server-Sent Events are popular communication protocols between a client like a web browser and a web server. First, let’s start with understanding what a standard HTTP web request looks like. Following are a sequence of events for regular HTTP request: Client opens a connection and requests data from the server. The server calculates the response. The server sends the response back to the client on the opened request. HTTP Protocol Ajax Polling Polling is a standard technique used by the vast majority of AJAX applications. The basic idea is that the client repeatedly polls (or requests) a server for data. The client makes a request and waits for the server to respond with data. If no data is available, an empty response is returned. Client opens a connection and requests data from the server using regular HTTP. The requested webpage sends requests to...

MonoLithic Vs Microservice Architecture | which Architecture should i choose ?

From last few years ,microservices are an accelerating trend . Indeed, microservices approach offers tangible benefits including an increase in scalability, flexibility, agility, and other significant advantages. Netflix, Google, Amazon, and other tech leaders have successfully switched from monolithic architecture to microservices. Meanwhile, many companies consider following this example as the most efficient way for business growth. On the contrary, the monolithic approach is a default model for creating a software application. Still, its trend is going down because building a monolithic application poses a number of challenges associated with handling a huge code base, adopting a new technology, scaling, deployment, implementing new changes and others. So is the monolithic approach outdated and should be left in the past? And is it worth shifting the whole application from a monolith to microservices ? Will developing a microservices application help you reach you...

Face Detection model on Image/Webcam/Video using Machine Learning OpenCV

Face detection is a computer technology that is being applied for many different applications that require the identification of human faces in digital images or video. It can be regarded as a specific case of object-class detection, where the task is to find the locations and sizes of all objects in an image that belongs to a given class. The technology is able to detect frontal or near-frontal faces in a photo, regardless of orientation, lighting conditions or skin color . Not Face Recognition! It’s about Detection. Face recognition describes a biometric technology that goes way beyond recognizing when a human face is present. It actually attempts to establish whose face it is. In this article, I’m not going deep into recognizing. I’ll keep that for a future blog article and for the time being, I’m going to explain how to run a simple Face  Detection program using your WebCam with Python Or we can run simple program on image as well . We are dealing with below Cascade models for...