Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, February 6, 2024

Program for URL, URL CONNECTION AND DATA GRAMS CONNECTION in JAVA

Objective : WRITE A  CODE FOR PROGRAM WITH  URL, URL CONNECTION AND  DATA GRAMS CONNECTION.
 

Code:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.URL;

import java.net.URLConnection;


public class url {

    public static void main(String[] args) {

        try {

            // URL Connection Example

            URL url = new URL("https://www.example.com");

            URLConnection urlConnection = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null) {

                System.out.println(inputLine);

            }

            in.close();


            // Datagram Socket Example

            DatagramSocket datagramSocket = new DatagramSocket();

            String message = "Hello from DatagramSocket";

            InetAddress address = InetAddress.getByName("localhost");

            byte[] sendData = message.getBytes();

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, 9876);

            datagramSocket.send(sendPacket);

            byte[] receiveData = new byte[1024];

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            datagramSocket.receive(receivePacket);

            String receivedMessage = new String(receivePacket.getData());

            System.out.println("Received from server: " + receivedMessage);

            datagramSocket.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}




No comments:

Post a Comment