[Go to site: main page, start]

100% found this document useful (1 vote)
27 views12 pages

Java Networking Basics and Socket Programming

Java networking allows connecting computing devices to share resources using sockets and protocols. Key aspects include IP addresses, port numbers, MAC addresses, connection-oriented vs connection-less protocols, and sockets. Java provides classes like Socket, ServerSocket, and DatagramSocket for networking. The URL and URLConnection classes represent web addresses and the connection between an application and a web resource.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
27 views12 pages

Java Networking Basics and Socket Programming

Java networking allows connecting computing devices to share resources using sockets and protocols. Key aspects include IP addresses, port numbers, MAC addresses, connection-oriented vs connection-less protocols, and sockets. Java provides classes like Socket, ServerSocket, and DatagramSocket for networking. The URL and URLConnection classes represent web addresses and the connection between an application and a web resource.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Java Networking

Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.

Java socket programming provides facility to share data between different computing
devices.

Advantage of Java Networking


1. sharing resources
2. centralize software management

Java Networking Terminology


The widely used java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. [Link] . It is


composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:

 TCP
 FTP
 Telnet
 SMTP
 POP etc.
3) Port Number

The port number is used to uniquely identify different applications. It acts as a


communication endpoint between applications.

The port number is associated with the IP address for communication between two
applications.

4) MAC Address

MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable


but slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not


reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communication.

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.

Java Socket programming can be connection-oriented or connection-less.

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

The client in socket programming must know two information:


1. IP Address of Server, and
2. Port number.

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.

Important methods

ethod Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.

Important methods

ethod Description

1) public Socket accept() returns the socket and establish a connection between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Let's see a simple of java socket programming in which client sends a text and server
receives it.
File: [Link]

1. import [Link].*;
2. import [Link].*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=[Link]();//establishes connection
8. DataInputStream dis=new DataInputStream([Link]());
9. String str=(String)[Link]();
10. [Link]("message= "+str);
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }

File: [Link]

1. import [Link].*;
2. import [Link].*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream([Link]());
8. [Link]("Hello Server");
9. [Link]();
10. [Link]();
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }

To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.

After running the client application, a message will be displayed on the server console.
Example of Java Socket Programming
(Read-Write both side)
In this example, client will write first to the server then server will receive and print the
text. Then server will write to the client and client will receive and print the text. The step
goes on.

File: [Link]

1. import [Link].*;
2. import [Link].*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=[Link]();
7. DataInputStream din=new DataInputStream([Link]());
8. DataOutputStream dout=new DataOutputStream([Link]());
9. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
10.
11. String str="",str2="";
12. while(![Link]("stop")){
13. str=[Link]();
14. [Link]("client says: "+str);
15. str2=[Link]();
16. [Link](str2);
17. [Link]();
18. }
19. [Link]();
20. [Link]();
21. [Link]();
22. }}

File: [Link]

1. import [Link].*;
2. import [Link].*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream([Link]());
7. DataOutputStream dout=new DataOutputStream([Link]());
8. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
9.
10. String str="",str2="";
11. while(![Link]("stop")){
12. str=[Link]();
13. [Link](str);
14. [Link]();
15. str2=[Link]();
16. [Link]("Server says: "+str2);
17. }
18.
19. [Link]();
20. [Link]();
21. }}

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:

A URL contains many information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, [Link] is the server name.
3. Port Number: It is an optional attribute. If we write
http//[Link]/sonoojaiswal/ , 80 is the port number. If port number is
not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, [Link] is the file name.

Commonly used methods of Java URL class


The [Link] class provides many methods. The important methods of URL class are given
below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.


public URLConnection openConnection() it returns the instance of URLConnection i.e. associated w

Example of Java URL class


1. //[Link]
2. import [Link].*;
3. import [Link].*;
4. public class URLDemo{
5. public static void main(String[] args){
6. try{
7. URL url=new URL("[Link]
8.
9. [Link]("Protocol: "+[Link]());
10. [Link]("Host Name: "+[Link]());
11. [Link]("Port Number: "+[Link]());
12. [Link]("File Name: "+[Link]());
13.
14. }catch(Exception e){[Link](e);}
15. }
16. }

Java URLConnection class


The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred
by the URL.

How to get the object of URLConnection class

The openConnection() method of URL class returns the object of URLConnection class.
Syntax:

1. public URLConnection openConnection()throws IOException{}


Displaying source code of a webpage by
URLConnecton class
The URLConnection class provides many methods, we can display all the data of a webpage
by using the getInputStream() method. The getInputStream() method returns all the data
of the specified URL in the stream that can be read and displayed.

Example of Java URLConnecton class


1. import [Link].*;
2. import [Link].*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("[Link]
7. URLConnection urlcon=[Link]();
8. InputStream stream=[Link]();
9. int i;
10. while((i=[Link]())!=-1){
11. [Link]((char)i);
12. }
13. }catch(Exception e){[Link](e);}
14. }
15. }

Java HttpURLConnection class


The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.

By the help of HttpURLConnection class, you can information of any HTTP URL such as
header information, status code, response code etc.

The [Link] is subclass of URLConnection class.

How to get the object of HttpURLConnection class

The openConnection() method of URL class returns the object of URLConnection class.
Syntax:

1. public URLConnection openConnection()throws IOException{}


You can typecast it to HttpURLConnection type as given below.

1. URL url=new URL("[Link]


2. HttpURLConnection huc=(HttpURLConnection)[Link]();

Java HttpURLConnecton Example


1. import [Link].*;
2. import [Link].*;
3. public class HttpURLConnectionDemo{
4. public static void main(String[] args){
5. try{
6. URL url=new URL("[Link]
7. HttpURLConnection huc=(HttpURLConnection)[Link]();
8. for(int i=1;i<=8;i++){
9. [Link]([Link](i)+" = "+[Link](i));
10. }
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }

Java InetAddress class


Java InetAddress class represents an IP address. The [Link] class provides
methods to get the IP of any host name for example [Link],
[Link], [Link] etc.

Commonly used methods of InetAddress class


Method Description

public static InetAddress getByName(String host) throws it returns the instance of InetAddress c
UnknownHostException LocalHost IP and name.

public static InetAddress getLocalHost() throws it returns the instance of InetAdddress


UnknownHostException host name and address.

public String getHostName() it returns the host name of the IP addr


public String getHostAddress() it returns the IP address in string form

Example of Java InetAddress class


Let's see a simple example of InetAddress class to get ip address of [Link]
website.

1. import [Link].*;
2. import [Link].*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=[Link]("[Link]");
7.
8. [Link]("Host Name: "+[Link]());
9. [Link]("IP Address: "+[Link]());
10. }catch(Exception e){[Link](e);}
11. }
12. }

Java DatagramSocket and


DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.

A datagram is basically an information but there is no guarantee of its content, arrival or


arrival time.
Commonly used Constructors of DatagramSocket
class
 DatagramSocket() throws SocketEeption: it creates a datagram socket and
binds it with the available Port Number on the localhost machine.
 DatagramSocket(int port) throws SocketEeption: it creates a datagram socket
and binds it with the given Port Number.
 DatagramSocket(int port, InetAddress address) throws SocketEeption: it
creates a datagram socket and binds it with the specified port number and host
address.

Java DatagramPacket class


Java DatagramPacket is a message that can be sent or received. If you send multiple
packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket


class
 DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
 DatagramPacket(byte[] barr, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by


DatagramSocket
1. //[Link]
2. import [Link].*;
3. public class DSender{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket();
6. String str = "Welcome java";
7. InetAddress ip = [Link]("[Link]");
8.
9. DatagramPacket dp = new DatagramPacket([Link](), [Link](), ip, 3000)
;
10. [Link](dp);
11. [Link]();
12. }
13. }
Example of Receiving DatagramPacket by
DatagramSocket
1. //[Link]
2. import [Link].*;
3. public class DReceiver{
4. public static void main(String[] args) throws Exception {
5. DatagramSocket ds = new DatagramSocket(3000);
6. byte[] buf = new byte[1024];
7. DatagramPacket dp = new DatagramPacket(buf, 1024);
8. [Link](dp);
9. String str = new String([Link](), 0, [Link]());
10. [Link](str);
11. [Link]();
12. }
13. }

Common questions

Powered by AI

The URL class in Java networking is significant as it represents a resource on the World Wide Web and provides the means to access that resource. It can extract various pieces of information from a given URL, including the protocol (e.g., http), the server name or IP address, the port number (if specified), and the file or directory name from the URL path. This allows Java applications to access and manipulate web resources programmatically .

Port numbers in Java networking serve to uniquely identify different applications running on the same machine. During communication, they are associated with IP addresses to facilitate the distinction between different network services and applications. Together, the IP address and port number create a unique endpoint for network communication allowing data to be directed to the correct application .

In Java networking, the MAC address is a unique identifier assigned to network interfaces for communications on the physical network segment, effectively functioning at the data link layer. In contrast, the IP address is a logical address assigned for host identification and location addressing at the network layer. Both are necessary because while the MAC address enables device identification and access on local networks, the IP address provides routing, ensuring packets can be sent across multiple networks, from source to target. Together, they facilitate reliable device connectivity and communication across diverse network structures .

The URLConnection class in Java provides a means for applications to communicate with a URL-provided resource, enabling both reading from and writing to it. When dealing with HTTP-specific requests, subclass HttpURLConnection extends URLConnection, facilitating additional features such as retrieving HTTP headers, handling response codes, and conducting HTTP-specific interactions like POST and GET requests. These classes form the backbone of Java's ability to interact seamlessly with web resources, allowing developers to fetch data, upload information, and manage network connections efficiently .

The ServerSocket and Socket classes in Java are used in connection-oriented socket programming, more specifically with TCP protocol. The ServerSocket class is designed for server use, where it listens for and establishes connections with client applications. Its main use is to accept incoming socket connection requests. Conversely, the Socket class is typically used on the client side to initiate and maintain connections to a server via its ServerSocket. While ServerSocket focuses on establishing connections, the Socket class is used for data transmission after the connection is made. Both are crucial for enabling reliable, bidirectional network communications .

In Java, the DatagramSocket and DatagramPacket classes function together to support connection-less socket programming, using UDP as the underlying protocol. A DatagramSocket is used to send and receive DatagramPackets, where the DatagramPacket class encapsulates the data either for sending or being received. While DatagramSocket provides a means to send and receive packets, the DatagramPacket holds the packet data, destination, and length information. Together, they allow Java applications to transmit data without a guaranteed delivery order or confirmation, suitable for real-time applications .

Java Socket Programming facilitates communication between applications by creating endpoints for two-way communication. There are two main types of socket programming in Java: connection-oriented and connection-less. Connection-oriented programming uses the Socket and ServerSocket classes, providing reliability through the use of TCP, a connection-oriented protocol. Connection-less programming employs the DatagramSocket and DatagramPacket classes, allowing for faster, but potentially less reliable communication by using UDP, a connection-less protocol .

The Java InetAddress class is used to encapsulate both the hostname and an IP address in Java applications. Its primary functions involve resolving domain names into their corresponding IP addresses and vice versa. This class supports hostname lookups via methods such as getByName, which fetches the IP address for a given hostname. Practical uses in networking applications include remote host connectivity checks, DNS lookups, and network diagnostics, which are essential for establishing TCP/IP connections or validation processes .

Java socket programming examples demonstrate concurrent bidirectional communication by employing both input and output streams for reading and writing data at both ends. For instance, a server may use DataInputStream to receive data from a client while maintaining a DataOutputStream for sending responses back. Concurrently, the client uses its own set of streams to continuously send and receive data. By maintaining these streams synchronously, a continuous conversation between the client and server is effectively established, showcasing a full-duplex communication channel .

A developer might choose a connection-less protocol over a connection-oriented protocol for applications that require speed over reliability, such as live audio or video streaming. Connection-less protocols, like UDP, do not involve setup of a long-term connection or confirmation of data receipt, making them faster but less reliable as they don't guarantee data arrival or order. The trade-off involves sacrificing reliability and data integrity of TCP in favor of the lower latency and higher throughput of UDP .

You might also like