Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Introduction for Java Input and Output

हर Programming Language में Input और Output का System होता है |Input और output के लिए stream का इस्तेमाि
ककया जाता है | अिग-अिग input और output के लिए java में एक package में ये input और output के classes define
ककये गए है और वो package है java.io |
Java बाइट stream और फाइि system के माध्यम से इनपट
ु और आउटपट
ु support करने के लिए कई आसान I/O
classes के साथ आता है . Java में हम files में डेटा को पढ़ सकते हैं और फाइिों में डेटा को लिख भी सकते हैं, Java
में कई इनपट
ु और आउटपट
ु stream हैं जो डेटा पढ़ने और लिखने के लिए उपयोग ककए जाते हैं।
Java प्रोग्रालमिंग language हमें कुछ ऐसी classes भी provide करती है जजनकी सहायता से हम input को ककसी भी
file से read कर सकते है और output को ककसी भी file में store करा सकते है .

For Example: यदि आप चाहे तो input console ना िेकर आप ककसी file से read कर सकते है . और output console
पर ना िे ख कर ककसी file में store करके िे ख सकते है , फाइल्स के द्वारा इनपट
ु और आउटपट
ु ऑपरे शन्स perform
करने के लिए आप stream का उपयोग करते है,

Data(byte) की sequence को stream कहा जाता है , Inputstream से input लिया जाता है , और Output
Stream से output लिया जाता है ।

Java file I/O को िो streams में ववभाजजत ककया गया है -


 Byte Streams
 Character Stream

MS- Programming in Java pg. 1


Byte Streams
ByteStream classes का उपयोग Input Stream से Bytes पढ़ने और OutputStream में bytes लिखने के
लिए ककया जाता है ।

यह byte के इनपट
ु और आउटपट
ु को सिंभािने के लिए सवु वधाजनक साधन प्रिान करता है byte streams
को 8-bit bytes से इनपट
ु और आउटपट
ु करने के लिए यज़
ू ककया जाता है ।

ByteStream क्िासेस का उपयोग करके हम वीडडयो, ऑडडयो, कैरे क्टर आदि को स्टोर कर सकते हैं। ये कक्षाएिं
java.io पैकेज का दहस्सा हैं।

ByteStream classes को िो प्रकार की classes में ववभाजजत ककया गया है ,

1) InputStream Class

InputStream Class फाइि, किंसोि या मेमोरी से bytes पढ़ने के तरीके प्रिान करता है । यह एक अमूतत वगत
है और इसे त्वररत नहीिं ककया जा सकता| , ववलभन्न कक्षाएिं InputStream classes को inherit करती हैं और
इसकी ववधधयों को override करती हैं। InputSream class के Subclass ननम्नलिखखत तालिका में दिए गए
हैं।

SN Class Description

1 BufferedInputStream This class provides methods to read bytes from the buffer.

2 ByteArrayInputStream This class provides methods to read bytes from the byte array.

3 DataInputStream This class provides methods to read Java primitive data types.

4 FileInputStream This class provides methods to read bytes from a file.

5 FilterInputStream This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.

6 ObjectInputStream This class provides methods to read objects.

7 PipedInputStream This class provides methods to read from a piped output stream
to which the piped input stream must be connected.

8 SequenceInputStream This class provides methods to connect multiple Input Stream and
read data from them.

The InputStream class contains various methods to read the data from an input stream. These
methods are overridden by the classes that inherit the InputStream class.

However, the methods are given in the following table.

MS- Programming in Java pg. 2


SN Method Description

1 int read() This method returns an integer, an integral representation of the next available
byte of the input. The integer -1 is returned once the end of the input is
encountered.

2 int read (byte buffer []) This method is used to read the specified buffer length bytes from the input and
returns the total number of bytes successfully read. It returns -1 once the end of
the input is encountered.

3 int read (byte buffer [], int This method is used to read the 'nBytes' bytes from the buffer starting at a
loc, int nBytes) specified location, 'loc'. It returns the total number of bytes successfully read from
the input. It returns -1 once the end of the input is encountered.

4 int available () This method returns the number of bytes that are available to read.

5 Void mark(int nBytes) This method is used to mark the current position in the input stream until the
specified nBytes are read.

6 void reset () This method is used to reset the input pointer to the previously set mark.

7 long skip (long nBytes) This method is used to skip the nBytes of the input stream and returns the total
number of bytes that are skipped.

8 void close () This method is used to close the input source. If an attempt is made to read even
after the closing, IOException is thrown by the method.

2) Output Stream
OutputStream एक abstract class है जजसका उपयोग Stream में 8-बबट bytes लिखने के लिए ककया जाता है । यह
सभी Output Stream क्िासों का सप
ु रक्िास है । इस class को instantiate नहीिं ककया जा सकता; हािााँकक, यह ववलभन्न
subclass द्वारा inherit ककया गए है जो ननम्नलिखखत तालिका में दिए गए हैं।

SN Class Description

1 BufferedOutputStream This class provides methods to write the bytes to the buffer.

2 ByteArrayOutputStream This class provides methods to write bytes to the byte array.

3 DataOutputStream This class provides methods to write the java primitive data types.

4 FileOutputStream This class provides methods to write bytes to a file.

5 FilterOutputStream This class provides methods to write to other output streams.

6 ObjectOutputStream This class provides methods to write objects.

7 PipedOutputStream It provides methods to write bytes to a piped output stream.

8 PrintStream It provides methods to print Java primitive data types.

MS- Programming in Java pg. 3


The OutputStream class provides various methods to write bytes to the output streams. The methods
are given in the following table.

SN Method Description

1 void write (int i) This method is used to write the specified single byte to the output
stream.

2 void write (byte buffer [] ) It is used to write a byte array to the output stream.

3 void write(bytes buffer[],int It is used to write nByte bytes to the output stream from the buffer
loc, int nBytes) starting at the specified location.

4 void flush () It is used to flush the output stream and writes the pending buffered
bytes.

5 void close () It is used to close the output stream. However, if we try to close the
already closed output stream, the IOException will be thrown by this
method.

Character Stream
Character stream का उपयोग करै क्टर data को रीड और write करने के लिए ककया जाता है . यह input और characters
के output को सिंभािने के लिए यह सवु वधाजनक साधन प्रिान करता है character stream यनू नकोड का उपयोग करता
है और इसलिए internationalization ककया जा सकता है ।
It is also divided into two categories:
1) Reader Class
Reader Class का उपयोग Input Stream से 16-बबट bytes को पढ़ने के लिए ककया जाता है । हािााँकक, यह एक
abstract class है और इसे instantiate नहीिं ककया जा सकता है, िेककन ऐसे कई subclass हैं जो Reader Class
को Inherit करते हैं और Reader class के methods को ओवरराइड करते हैं। Reader class की सभी methods
IOException throw करता हैं। ReaderClass के Subclass ननम्नलिखखत तालिका में दिए गए हैं।

SN Class Description

1. BufferedReader This class provides methods to read characters from the buffer.

2. CharArrayReader This class provides methods to read characters from the char array.

3. FileReader This class provides methods to read characters from the file.

4. FilterReader This class provides methods to read characters from the underlying character input
stream.

5 InputStreamReader This class provides methods to convert bytes to characters.

6 PipedReader This class provides methods to read characters from the connected piped output
stream.

7 StringReader This class provides methods to read characters from a string.

MS- Programming in Java pg. 4


The Reader class methods are given in the following table.

SN Method Description

1 int read() This method returns the integral representation of the next character present in the
input. It returns -1 if the end of the input is encountered.

2 int read(char buffer[]) This method is used to read from the specified buffer. It returns the total number
of characters successfully read. It returns -1 if the end of the input is encountered.

3 int read(char buffer[], This method is used to read the specified nChars from the buffer at the specified
int loc, int nChars) location. It returns the total number of characters successfully read.

4 void mark(int nchars) This method is used to mark the current position in the input stream until nChars
characters are read.

5 void reset() This method is used to reset the input pointer to the previous set mark.

6 long skip(long nChars) This method is used to skip the specified nChars characters from the input stream
and returns the number of characters skipped.

7 boolean ready() This method returns a boolean value true if the next request of input is ready.
Otherwise, it returns false.

8 void close() This method is used to close the input stream. However, if the program attempts
to access the input, it generates IOException.

2) Writer Class
Output Stream में 16-बबट यनू नकोड character लिखने के लिए writer class का उपयोग ककया जाता है । Writer
class की ववधधयााँ IOException उत्पन्न करती हैं। Reader class की तरह, Writer class भी एक abstract class
है जजसे instantiate नहीिं ककया जा सकता है ; इसलिए, writer class के subclass का उपयोग Output Stream पर
character लिखने के लिए ककया जाता है । Writer class के subclass नीचे तालिका में दिए गए हैं।

SN Class Description

1 BufferedWriter This class provides methods to write characters to the buffer.

2 FileWriter This class provides methods to write characters to the file.

3 CharArrayWriter This class provides methods to write the characters to the character array.

4 OutpuStreamWriter This class provides methods to convert from bytes to characters.

5 PipedWriter This class provides methods to write the characters to the piped output
stream.

6 StringWriter This class provides methods to write the characters to the string.

To write the characters to the output stream, the Write class provides various methods given in the
following table.

MS- Programming in Java pg. 5


SN Method Description

1 void write() This method is used to write the data to the output stream.

2 void write(int i) This method is used to write a single character to the output stream.

3 void write(char buffer[]) This method is used to write the array of characters to the output stream.

4 void write(char buffer This method is used to write the nChars characters to the character array
[],int loc, int nChars) from the specified location.

5 void close () This method is used to close the output stream. However, this generates
the IOException if an attempt is made to write to the output stream after
closing the stream.

6 void flush () This method is used to flush the output stream and writes the waiting
buffered characters.

System Class Basic I/O Console तीन प्रकार के है |

1. System.out : ये एक Output Stream(Monitor) है | इससे data को output करने के लिए इस्तेमाि ककया जाता है |
2. System.in : ये एक input Stream (Keyboard)है | इससे data को input करने के लिए इस्तेमाि ककया जाता है |
3. System.err : ये एक error Stream (by default Monitor) है | ये System.out के तरह ही होता है | ये लसफत error को
output करने के लिए इस्तेमाि होता है |

Example for System.out and System.err

public class Sample{


public static void main(String[] args) {
System.out.println("Hello World");
System.err.println("Error");
}
}

Note : System.err , data console पर Error की जगह पर print हुआ है |

MS- Programming in Java pg. 6


Example
Example for Reading file using BufferedInputStream
यहााँ पर stream से data read करने के लिए BufferedStream का इस्तेमाि ककया जाता है |
file.txt

Example for BufferedInputStream.

Source Code :

import java.io.*;
public class Sample{
public static void main(String args[])
{
try{
FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int i;
while((i=bis.read())!=-1){
System.out.print((char)i);
}
fis.close();
bis.close();
}catch(FileNotFoundException e1){
System.out.println("File is not Found");
}
catch(Exception e2){
System.out.println("Reading File Error");
}
}
}

Output :

Example For BufferdInputStream.

MS- Programming in Java pg. 7


Example for Writing file using BufferedOutputStream
BufferedOutputStream को data store करने के लिए internal buffer का इस्तेमाि ककया जाता है |
Source Code :

import java.io.*;
public class Sample{
public static void main(String args[])
{
try{
FileOutputStream fos = new FileOutputStream("file1.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
String str = "Example for BufferedOutputStream.";

byte by[] = str.getBytes();


bos.write(by);
bos.close();
fos.close();
System.out.println("File is created successfully");
}
catch(Exception e){
System.out.println("File is not created");
}
}
}

Output :

File is created successfully

file1.txt

Example for BufferedOutputStream.

MS- Programming in Java pg. 8


Writing on File Using DataOutputStream
DataOutputStream से standard data type से data को write ककया जाता है |

import java.io.*;
public class Sample {
public static void main(String args[])
{
int id = 1; //this data written to file
String emp_name = "Rakesh Sharma";
float salary = 50000.52f;
try {
FileOutputStream fos = new FileOutputStream("file.txt");
DataOutputStream dos = new DataOutputStream(fos);

dos.writeInt(id);
dos.writeUTF(emp_name);
dos.writeFloat(salary);

dos.close();
System.out.println("Data written successfully.");

}catch(IOException e){
System.out.println(e);
}
}
}

Output :

Data written successfully.

file.txt

1 Rakesh SharmaGCP…

MS- Programming in Java pg. 9


Reading File Using DataInputStream
DatainputStream से standard (primitive) data type से data को read ककया जाता है |
Source Code :

import java.io.*;
class Sample1{
public static void main(String[] args)
{
try{
FileInputStream fis = new FileInputStream("file.txt");
DataInputStream dis = new DataInputStream(fis);

System.out.println("id : " + dis.readInt());


System.out.println("Name : " + dis.readUTF());
System.out.println("Salary : " + dis.readFloat());

}catch(IOException e) {
System.out.println(e);
}
}
}

file.txt

Rakesh SharmaGCP…

Output :

id : 1
Name : Rakesh Sharma
Salary : 50000.52

MS- Programming in Java pg. 10


Writing on File Using FileOutputStream
Source Code :

import java.io.*;
public class Sample {

public static void main(String args[]){


try{
FileOutputStream fos=new FileOutputStream("file.txt");
String str="Hello World!";
byte b[]=str.getBytes();

fos.write(b);
fos.close();
System.out.println("File written successfully");
}catch(Exception e){
System.out.println(e);
}
}
}

Output :

Data written successfully.

file.txt

Hello World!

MS- Programming in Java pg. 11


Reading File Using FileInputStream
file.txt

Hello World!

Source Code :

import java.io.*;

public class Sample {


public static void main(String args[])
{
try{
FileInputStream fis=new FileInputStream("file.txt");
int i=0;
while((i=fis.read())!=-1){
System.out.print((char)i);
}
fis.close();
}catch(Exception e){
System.out.println(e);
}
}
}

Output :

Hello World!

MS- Programming in Java pg. 12


Writing on File Using PrintStream
Source Code :

import java.io.*;
public class Sample{
public static void main(String args[])
{
try{
FileOutputStream fos = new FileOutputStream("file.txt");
PrintStream ps = new PrintStream(fos);
ps.println("Hello World!");
ps.close();
fos.close();
System.out.println("Data Written Successfully");
}catch(Exception e){
System.out.println(e);
}
}
}

Output :

File written successfully.

file.txt

Hello World!

MS- Programming in Java pg. 13


Different Ways to Copy Content From One File to Another File
जावा में , हम एक फाइि की सामग्री को िस
ू री फाइि में कॉपी कर सकते हैं। यह
FileInputStream और FileOutputStream कक्षाओिं द्वारा ककया जा सकता है ।

FileInputStream क्िास

यह एक बाइट इनपुट स्रीम क्िास है जो ककसी फाइि से बाइट्स को पढ़ने में मिि करती है । यह
ककसी फाइि से डेटा पढ़ने के लिए ववलभन्न तरीके प्रिान करता है ।
FileInputStream fin = new FileInputStream(filename);

यह एक FileInputStream ऑब्जेक्ट कफन बनाता है , जजसे एक फाइि नाम दिया जाता है , जहािं से
यह सामग्री की copy बनाएगा या रीड ऑपरे शन करे गा।

Methods used:
1. read(): इस ववधध का उपयोग डेटा की बाइट को पढ़ने के लिए ककया जाता है । यह उस बाइट को
integer value के रूप में return करता है या फाइि के अिंत तक पहुिंचने पर -1 return करता है ।
2. close(): इस ववधध का उपयोग FileInputStream को बिंि करने के लिए ककया जाता है ।

FileOutputStream Class
यह एक बाइट आउटपुट स्रीम क्िास है जो फाइि में बाइट्स लिखने में मिि करता है । यह ककसी फाइि
में डेटा लिखने के लिए ववलभन्न methods प्रिान करता है ।

FileOutputStream fout = new FileOutputStream(filename);


यह फाइिनाम दिए बबना एक FileOutputStream ऑब्जेक्ट बनाता है जजस पर यह पढ़ी गई
content लिखेगा।

Methods used:
1. write(): इस ववधध का उपयोग FileOutputStream पर डेटा की एक बाइट लिखने के लिए
ककया जाता है ।
2. close(): इस ववधध का उपयोग FileInputStream को बिंि करने के लिए ककया जाता है ।

File Class
File f = new File(filename);

यह f नामक एक File ऑब्जेक्ट बना है , जजसे एक String ऑब्जेक्ट दिया जाता है जो उस File
का फाइि नाम या path होता है जजसे एक्सेस ककया जाना है ।

नोट: यदि यहािं दिया गया फाइि नाम मौजूि नहीिं है , तो File class उस नाम की एक नई फाइि
बनाएगा।

MS- Programming in Java pg. 14


Example:
// Java program to copy content from one file to another
import java.io.*;
import java.util.*;

public class CopyFromFileaToFileb {


public static void copyContent(File a, File b) throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
while ((n = in.read()) != -1) {
out.write(n);
}
}
finally {
in.close();
out.close(); // close() function to close the stream
}
System.out.println("File Copied");
}

public static void main(String[] args) throws Exception


{
Scanner sc = new Scanner(System.in);

// get the source file name


System.out.println("Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();

// source file
File x = new File(a);

// get the destination file name


System.out.println( "Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();

// destination file
File y = new File(b);

// method called to copy the


// contents from x to y
copyContent(x, y);
}
}

Output
Enter the source filename from where you have to read/copy :
sourcefile.txt
Enter the destination filename where you have to write/paste :
destinationfile.txt
File Copied
Source File
MS- Programming in Java pg. 15
Source File

Destination File

Destination File

Networking क्या है
जब िो या िो से अधधक computers और Networking device ककसी भी communication channel के माध्यम से
Data transmission और Resource sharing करने के लिए एक िस
ु रे से linked होते हैं यानन की connect होते हैं
तब उसे Network या Computer Network या Data Network कहा जाता है |

Networking in Java

Java में नेटवककिंग का मतिब होता है कक आप अिगअिग किंप्यट


ू र या डडवाइस के बीच नेटवकत कनेक्शन बना -
सकते हैं, उन्हें manage कर सकते हैं, और नेटवकत के माध्यम से डेटा transfer कर सकते हैं। Java में नेटवककिंग के
लिए महत्वपर्
ू त िाइब्रेरी और क्िासेस उपिब्ध हैं, जजनका उपयोग आपके एजप्िकेशन में नेटवकत सिंबधिं धत कायों को
िागू करने में ककया जा सकता है ।

Java.net पैकेज िो सामान्य नेटवकत प्रोटोकॉि के लिए support provide करता है :

TCP: TCP (Transmission Control Protocol) जो ववश्वसनीय सिंचार की अनम


ु नत िे ता है
िो Application के बीच. TCP का उपयोग आमतौर पर इिंटरनेट प्रोटोकॉि पर ककया जाता है, जजसे Connect ककया
जाता है TCP/IP के रूप में ।

UDP: UDP का मतिब यज


ू र डेटाग्राम प्रोटोकॉि है, जो एक कनेक्शन-रदहत प्रोटोकॉि है जो इसकी अनम
ु नत िे ता है
अनप्र
ु योगों के बीच सिंचाररत ककए जाने वािे डेटा के पैकेट।

MS- Programming in Java pg. 16


Java Networking classes

जावा प्रोग्रालमिंग भाषा के java.net पैकेज में ववलभन्न classes शालमि हैं जो नेटवकत resources
तक पहुिंचने के लिए उपयोग में आसान साधन प्रिान करती हैं। Java.net पैकेज में शालमि
classes इस प्रकार हैं –

1. DatagramPacket – The DatagramPacket class is used to provide a facility for the


connectionless transfer of messages from one system to another.

2. InetAddress – The InetAddress class is used to provide methods to get the IP


address of any hostname.

3. Server Socket – The ServerSocket class is used for implementing system-


independent implementation of the server-side of a client/server Socket Connection.

4. Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations.

5. DatagramSocket – The DatagramSocket class is a network socket that provides a


connection-less point for sending and receiving packets.

6. URL – The URL class in Java is the entry point to any available sources on the
internet. A Class URL describes a Uniform Resource Locator, which is a signal to a
“resource” on the World Wide Web.

7. URLConnection – The URLConnection class in Java is an abstract class describing a


connection of a resource as defined by a similar URL.

Java Socket Programming


Socket नेटवकत पर चि रहे िो प्रोग्रामों के बीच two way communication लििंक का एक end point है ।
Socket Inter Process Communicatoin (IPC) का एक साधन प्रिान करता है जजसके बीच सिंचार होता है ।

Socket and ServerSocket classes are used for connection-oriented(TCP) socket programming
DatagramSocket and DatagramPacket classes are used for connection-less (UDP) socket programming.

MS- Programming in Java pg. 17


The client in socket programming must know two information:

1. IP Address : IP address इिंटरनेट पर उपयोगकतात (user) की पहचान होती है । इसे निंबरों (0-255) से िशातया जाता है । जजस
प्रकार एक घर या ऑकफस का एड्रेस होता है उसी प्रकार इिंटरनेट support करने वािे डडवाइस का भी अपना एक एड्रेस
होता है । जजसे हम IP address कहते हैं

2. Port number. पोटत निंबर एक specific process/program की पहचान करने का एक तरीका है जजसमें सवतर
पर आने पर इिंटरनेट या अन्य नेटवकत सिंिेश को अग्रेवषत ककया जाना है ।

Java में सॉकेट प्रोग्रालमिंग एक तरीका है जजसका उपयोग नेटवकत कम्यनु नकेशन के लिए ककया जाता है , जैसे
कक डेटा को एक किंप्यट
ू र से िस
ू रे किंप्यट
ू र तक भेजने या प्राप्त करने के लिए। सॉकेट प्रोग्रालमिंग का उपयोग
ववलभन्न प्रकार की नेटवकत ऐजप्िकेशन्स बनाने के लिए ककया जा सकता है , जैसे कक वेब सवतर, वेब क्िाइिंट,
चैट ऐजप्िकेशन, फाइि रािंसफर, और और भी बहुत कुछ। Socket प्रोग्रालमिंग का मख्
ु य उद्िे श्य िो किंप्यट
ू रों के
बीच नेटवकत के माध्यम से डेटा के आिान-प्रिान को सिंभािना है । इसमें िो मख्
ु य भाग होते हैं:
1. सवतर (Server): सवतर सॉकेट एक किंप्यूटर पर चिता है जो अनुरोधों को सुनता है और प्रनतकिया िे ता है ।
सवतर सॉकेट ककसी ववलशष्ट पोटत पर खि
ु ा रहता है और उस पोटत पर आगिंतुकों के साथ कनेक्ट होता है ।
2. क्िाइिंट (Client): क्िाइिंट सॉकेट एक अन्य किंप्यूटर पर चिता है जो सवतर के साथ कनेक्ट होने का अनुरोध
करता है और डेटा भेजता है या प्राप्त करता है ।

>Java सॉकेट प्रोग्रालमिंग में Socket और ServerSocket क्िासेस का उपयोग ककया जाता है ।

>एक सवतर सॉकेट बनाने के लिए, आपको ServerSocket क्िास का उपयोग करना होता है ,
जबकक क्िाइिंट सॉकेट बनाने के लिए आपको Socket क्िास का उपयोग करना होता है । क्िाइिंट
सॉकेट उस सवतर सॉकेट से कनेक्ट होकर डेटा का आिान-प्रिान कर सकता है ।

Socket class
सॉकेट मशीनों के बीच Communication के लिए बस एक end point है । सॉकेट क्िास का उपयोग सॉकेट
बनाने के लिए ककया जा सकता है ।
Important methods
Method Description

1) public InputStream getInputStream() इस Socket से जुडा इनपट


ु स्रीम object िौटाता है ।

2) public OutputStream getOutputStream() इस Socket से जुडा आउटपट


ु स्रीम object िौटाता है ।

3) public synchronized void close() इस Socket को बिंि कर िे ता है

MS- Programming in Java pg. 18


ServerSocket class
Server Socket बनाने के लिए ServerSocket क्िास का उपयोग ककया जा सकता है । इस ऑब्जेक्ट का
उपयोग client के साथ connection स्थावपत करने के लिए ककया जाता है ।
Important methods
Method Description

1) public Socket accept() सवतर और क्िाइिंट के बीच connection स्थावपत करता है और Socket object
return करता है ।

2) public synchronized void server socket close करता है ।


close()

Example of Java Socket Programming


Creating Server:

सवतर एजप्िकेशन बनाने के लिए, हमें सवतरसॉकेट क्िास का object बनाना होगा। यहािं, हम क्िाइिंट और सवतर
के बीच सिंचार के लिए 6666 पोटत निंबर का उपयोग कर रहे हैं। आप कोई अन्य पोटत निंबर भी चन
ु सकते हैं.
accept() ववधध क्िाइिंट की प्रतीक्षा करती है । यदि क्िाइिंट दिए गए पोटत निंबर से जुडता है , तो यह सॉकेट का
एक instance िौटाता है ।

1. ServerSocket ss=new ServerSocket(6666);


2. Socket s=ss.accept();//establishes connection and waits for the client

MS- Programming in Java pg. 19


Creating Client:

क्िाइिंट एजप्िकेशन बनाने के लिए, हमें सॉकेट क्िास का object बनाना होगा। यहािं, हमें सवतर का IP address
या Hostname और एक Port Number पास करना होगा। यहािं, हम "localhost" / 127.0.01 का उपयोग कर
रहे हैं क्योंकक हमारा सवतर उसी लसस्टम पर चि रहा है ।

1. Socket s=new Socket("localhost",6666);

जावा सॉकेट प्रोग्रालमिंग का एक सरि उिाहरर् िे खें जहािं क्िाइिंट एक टे क्स्ट भेजता है और सवतर इसे प्राप्त करता है और
वप्रिंट करता है।

File: MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

File: MyClient.java

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
MS- Programming in Java pg. 20
dout.close();
s.close();
}
catch(Exception e){System.out.println(e);}
}
}

इस प्रोग्राम को Execute करने के लिए िो कमािंड प्रॉम्प्ट खोिें और प्रत्येक प्रोग्राम को प्रत्येक कमािंड प्रॉम्प्ट पर
execute करें जैसा कक नीचे दिए गए धचत्र में दिखाया गया है ।क्िाइिंट एजप्िकेशन चिाने के बाि, सवतर किंसोि पर एक

सिंिेश प्रिलशतत होगा।

MS- Programming in Java pg. 21


Two Way Communication(Socket Programming)
MyServer.java
import java.net.*;
import java.io.*;
import java.util.*;
public class MyServer{
public static void main(String[] args) throws IOException{
ServerSocket ss=new ServerSocket(4444);
System.out.println("server is ready");
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
Scanner sc=new Scanner(System.in);
String msg;
do{
msg=dis.readUTF();
System.out.println("client: "+msg);
System.out.print("Server: ");
msg=sc.nextLine();
dos.writeUTF(msg);

}while(!msg.equals("over"));

s.close();
ss.close();
}
}

MS- Programming in Java pg. 22


import java.net.*;
import java.io.*;
import java.util.*;

public class MyClient {

public static void main(String[] args)throws IOException {

Socket s=new Socket("192.168.107.197",4444); //Sever IP address and Port No.


DataOutputStream dos=new DataOutputStream(s.getOutputStream());
DataInputStream dis=new DataInputStream(s.getInputStream());
Scanner sc=new Scanner(System.in);
System.out.println("client is ready to send msg");
String msg;
do{
System.out.print("client: ");
msg=sc.nextLine();
dos.writeUTF(msg);
msg=dis.readUTF();
System.out.println("server: "+msg);

}while(!msg.equals("over"));

s.close();

}
//Output: Both client and server can send or receive message

Java URL
java URL class जो है वह URL को प्रस्तुत करती है . URL का पूरा नाम Uniform resource locator होता है .
java URL class इन्टरनेट पर उपिब्ध resources के लिए एक gateway की तरह कायत करता है .
URL क्या होता है?
url जो है वह webpage का वेब एड्रेस होता है . इन्टरनेट में ककसी भी वेबसाइट को खोिने के लिए url का
प्रयोग ब्राउज़र के द्वारा ककया जाता है . प्रत्येक वेबसाइट के सभी web pages का एक यूननक url होता है .
जैसे:- https://www.abc.com/category/java-in-hindi/
जहााँ http एक प्रोटोकॉि है , abc.com एक सवतर का नाम है और category/java-in-hindi/ फाइि का नाम है .
methods of java URL class:-
java url class में मुख्य रूप से ननम्नलिखखत methods का प्रयोग ककया जाता है .
1:- public string getProtocol():- यह URL के प्रोटोकॉि को return करता है .

MS- Programming in Java pg. 23


2:- public string getHost():- यह url के hostname को ररटनत करता है .
3:- public string getPort():- यह URL के port निंबर को ररटनत करता है .
4:- public string getFile():- यह url के filename को ररटनत करता है .
5:- public URLConnection openConnection():- यह URLConnection के ऑब्जेक्ट को ररटनत करता है .
उदाहरण के लिए प्रोग्राम:-
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL(“https://abc.com/category/java-in-hindi/”);
System.out.println(“Protocol: “+url.getProtocol());
System.out.println(“Host Name: “+url.getHost());
System.out.println(“Port Number: “+url.getPort());
System.out.println(“File Name: “+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}

OUTPUT
Protocol: https
HostName: abc.com
Port Number: …
File Name: java-in-hindi

URLConnection class
जावा URLConnection class, URL और एजप्िकेशन के बीच एक communication लििंक का represent करता है । इसका
उपयोग URL द्वारा specified resource पर डेटा को पढ़ने और लिखने के लिए ककया जा सकता है ।

URLConnection क्िास की विशेषताएं


URLConnection एक abstract class है । िो subclass HttpURLConnection और JarURLConnection इिंटरनेट पर क्िाइिंट
जावा प्रोग्राम और URL resources के बीच connection बनाते हैं।
URLConnection क्िास की सहायता से, user ककसी URL Objects द्वारा referenced ककसी भी सिंसाधन को पढ़ और
लिख सकता है ।
एक बार जब कनेक्शन स्थावपत हो जाता है और जावा प्रोग्राम में URLConnection ऑब्जेक्ट होता है, तो हम इसका
उपयोग पढ़ने या लिखने या content की length आदि जैसी अधधक जानकारी प्राप्त करने के लिए कर सकते हैं।

MS- Programming in Java pg. 24


Constructors
Constructor Description

1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.

URLConnection Class Methods


Method Description

void connect() It opens a communications link to the resource referenced by this URL, if
such a connection has not already been established.

int getConnectionTimeout() It returns setting for connect timeout.

Object getContent() It retrieves the contents of the URL connection.

String getContentType() It returns the value of the date header field.

InputStream It returns an input stream that reads from the open condition.
getInputStream()

OutputStream It returns an output stream that writes to the connection.


getOutputStream()

URL getURL() It returns the value of the URLConnection's URL field.

How to get the object of URLConnection Class

URL क्िास की openConnection() ववधध URLConnection क्िास का ऑब्जेक्ट िौटाती है ।

Syntax:

public URLConnection openConnection()throws IOException{}

MS- Programming in Java pg. 25


Displaying Source Code of a Webpage by URLConnecton Class
URLConnection class कई methods प्रिान करता है । हम getInputStream() method का उपयोग करके
ककसी वेबपेज का सारा डेटा प्रिलशतत कर सकते हैं। यह स्रीम में specific URL का सारा डेटा िौटाता है जजसे
पढ़ा और प्रिलशतत ककया जा सकता है ।
Example of Java URLConnection Class
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

OUTPUT
//Source code of a webpage in HTML TAG, CSS , scripts etc

MS- Programming in Java pg. 26

You might also like