|
| Advance Java | IndianTechnoEra |
Networking in Java:
Networking in Java refers to the process of establishing communication between different devices on a network using the Java programming language.
The Java platform provides a set of APIs in the java.net package that enables developers to implement networked applications.
Networking Fundamentals with Java:
Networking fundamentals refer to the concepts and principles underlying computer networks.
These include the various layers of the network protocol stack, such as the physical, data link, network, transport, and application layers.
Networking Basics:
Networking is the practice of connecting devices together to share information.
It is made up of hardware, software, and protocols that allow devices to communicate with each other. The main components of a networking system are:
- Network Interface Cards (NICs) - hardware devices that connect devices to a network
- Switches and Routers - hardware devices that manage the flow of data between devices on a network
- Transmission Media - physical media that carries data between devices, such as wires or wireless signals
- Network Protocols - sets of rules and standards that govern how data is transmitted and received between devices on a network
TCP/IP Protocol Suite:
The TCP/IP protocol suite is the foundation of the Internet and is used to transmit data over the Internet. It is made up of two main protocols:
- Transmission Control Protocol (TCP) - a connection-oriented protocol that ensures reliable delivery of data by establishing a connection between devices before transmitting data
- Internet Protocol (IP) - a connectionless protocol that provides a unique address for each device on a network and is responsible for routing data between devices
Socket Programming:
Socket programming is a way to communicate over a network using sockets, which provide a way for programs to send and receive data over a network.
In Java, socket programming is implemented using the java.net package, which provides classes for creating and managing sockets.
Java Networking APIs:
Java provides a set of networking APIs that make it easy to create networked applications.
The main classes in the Java networking API include:
- InetAddress - represents an IP address
- DatagramSocket and DatagramPacket - used to send and receive UDP packets
- Socket and ServerSocket - used to create TCP connections between devices
Advanced Java Networking Concepts:
Advanced Java networking concepts include:
- Multithreaded Servers - servers that can handle multiple clients simultaneously by using multiple threads to handle incoming requests
- Non-blocking I/O - a technique for handling I/O operations asynchronously, without blocking the application's main thread
- Remote Method Invocation (RMI) - a Java-specific protocol for calling methods on remote objects, allowing Java programs to interact with each other over a network
Overall, understanding the fundamentals of networking is important for Java developers who want to create networked applications. Java's networking APIs make it easy to create networked applications, and understanding advanced concepts like multithreaded servers and non-blocking I/O can help developers create highly scalable and efficient networked applications.
Internet Addresses:
An internet address is a unique identifier that identifies a device on the internet.
In Java, the InetAddress class provides methods to represent and manipulate internet addresses.
In Java, the InetAddress class is used to represent an Internet address.
It has methods to get the hostname, and IP address, and to resolve a hostname to an IP address.
There are two types of Internet addresses in networking in Java:
- IPv4 and
- IPv6 addresses.
IPv4 addresses:
IPv4 addresses are 32-bit addresses represented in dotted-decimal notation (for example, 192.168.0.1).
IPv4 addresses are widely used and are the most common type of Internet address.
They have a limited number of unique addresses, which is why IPv6 was developed.
IPv6 addresses:
IPv6 addresses are 128-bit addresses represented in hexadecimal notation (for example, 2001:0db8:85a3:0000:0000:8a2e:0370:7334).
IPv6 addresses provide a much larger address space than IPv4 addresses, which allows for more unique addresses.
However, not all devices and networks support IPv6 yet.
Networking Classes and Interfaces:
Networking Classes and Interfaces using java.net package:
The java.net package provides a range of classes and interfaces to implement networked applications,
Networking Classes: Socket, ServerSocket, DatagramSocket, DatagramPacket, URL, and HttpURLConnection classes,
Networking Interfaces: URLConnection, and SocketAddress interfaces.
Create IntAddress Object:
To create an InetAddress object in Java, you can use one of the following methods of the InetAddress class:
1. getByName(): This method takes a hostname or IP address as a string argument and returns an InetAddress object representing that address.
InetAddress address = InetAddress.getByName("www.google.com");
2. getByAddress(): This method takes an array of bytes representing the address and returns an InetAddress object representing that address.
byte[] ip = new byte[]{(byte) 192, (byte) 168, 0, 1};
InetAddress address = InetAddress.getByAddress(ip);
Access IntAddress Object:
Once you have an InetAddress object, you can use its methods to get information about the address. Here are some commonly used methods:
1. getHostName(): This method returns the hostname of the address.
String hostname = address.getHostName();
2. getHostAddress(): This method returns the IP address of the address as a string.
String ip = address.getHostAddress();
3. isReachable(): This method tests whether the address is reachable.
boolean reachable = address.isReachable(5000); // timeout in milliseconds
Example: InetAddress:
import java.net.*;
public class InetAddressExample {
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println("Host name: " + address.getHostName());
System.out.println("IP address: " + address.getHostAddress());
}
}
Classes in java.net:
URL: This class represents a Uniform Resource Locator (URL), which is a reference to a web resource.
URLConnection: This class provides methods for establishing and managing a connection to a remote server, and for sending and receiving data over the network.
HttpURLConnection: This class extends URLConnection and provides methods for working with HTTP connections.
Socket: This class represents a socket, which is an endpoint for sending and receiving data over the network.
ServerSocket: This class represents a server socket, which listens for incoming connections from clients.
DatagramSocket: This class represents a datagram socket, which provides low-level support for sending and receiving datagrams (packets) of data.
DatagramPacket: This class represents a packet of data that is sent or received over the network via a DatagramSocket.
InetAddress: This class represents an IP address and a hostname, and provides methods for getting and setting information about IP addresses and hostnames.
URI: This class represents a Uniform Resource Identifier (URI), which is a compact sequence of characters that identifies an abstract or physical resource.
URLDecoder: This class provides methods for decoding a URL-encoded string.
URLEncoder: This class provides methods for encoding a string for use in a URL.
Proxy: This class represents a proxy server, which is an intermediary server between a client and a server thatfacilitates network communication.
SocketAddress: This class represents a socket address, which consists of an IP address and a port number.
InetSocketAddress: This class represents a socket address with a hostname or IP address and a port number.
URLStreamHandler: This class provides an interface for handling streams for a given URL.
URLStreamHandlerFactory: This class provides methods for creating instances of URLStreamHandler objects.
Interfaces in java.net:
Here are the interfaces available in the java.net package:
URLStreamHandler: This interface defines methods for opening and managing a stream for a given URL.
ContentHandler: This interface defines methods for parsing and handling content types in network connections.
FileNameMap: This interface defines methods for mapping between MIME types and filenames.
SocketOption: This interface defines methods for setting and getting socket options.
SocketImplFactory: This interface defines methods for creating new instances of SocketImpl objects, which provide low-level socket support.
URLConnection: This interface defines methods for establishing and managing a connection to a remote server, and for sending and receiving data over the network.
CookiePolicy: This interface defines methods for managing cookies in network connections.
CookieStore: This interface defines methods for storing and retrieving cookies in network connections.
DatagramSocketImplFactory: This interface defines methods for creating new instances of DatagramSocketImpl objects, which provide low-level datagram socket support.
ProxySelector: This interface defines methods for selecting a proxy server for network connections.
SocketAddress: This interface defines methods for representing a socket address, which consists of an IP address and a port number.
DatagramSocketImpl: This interface provides low-level support for datagram sockets.
Sockets:
A socket is an endpoint for sending and receiving data between devices on a network.
In Java, the Socket class provides methods to create and manipulate sockets.
Example: Sockets Demo
This example code demonstrates how to connect to the Google web server and send an HTTP GET request to retrieve the homepage.
Client/Server Model:
In the client/server model, one device (the client) requests a service from another device (the server).
The server then provides the service, and the client receives the result.
Java provides a range of APIs to create both client and server applications.
Example: client-server model:
Explain the Client Code
Socket socket = new Socket("localhost", 1234); - This line creates a new Socket object and connects it to the server running on the local machine at port number 1234.
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); - This line creates a new PrintWriter object that writes to the output stream of the socket.
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - This line creates a new BufferedReader object that reads from the input stream of the socket.
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); - This line creates a new BufferedReader object that reads from the standard input stream, which is typically the keyboard.
while ((userInput = stdIn.readLine()) != null) { - This line begins a while loop that reads input from the standard input stream until the user enters a null value (e.g., by pressing Ctrl-D).
out.println(userInput); - This line sends the user's input to the server via the output stream of the socket.
System.out.println("Server says: " + in.readLine()); - This line reads a response from the server via the input stream of the socket and prints it to the console.
The while loop continues to prompt the user for input, send it to the server, and read responses from the server until the user enters a null value or the connection is terminated.
Explain the Server Code:
ServerSocket serverSocket = new ServerSocket(1234); - This line creates a new ServerSocket object that listens for incoming connections on port number 1234.
System.out.println("Server is listening on port 1234"); - This line prints a message to the console indicating that the server is listening on port number 1234.
Socket clientSocket = serverSocket.accept(); - This line blocks until a client connects to the server and then returns a new Socket object for communicating with the client.
System.out.println("Client connected: " + clientSocket.getInetAddress()); - This line prints a message to the console indicating that a client has connected to the server and displays the IP address of the client.
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - This line creates a new BufferedReader object that reads from the input stream of the socket connected to the client.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); - This line creates a new PrintWriter object that writes to the output stream of the socket connected to the client.
String inputLine; - This line declares a new String variable called inputLine.
while ((inputLine = in.readLine()) != null) { - This line begins a while loop that reads input from the client via the input stream of the socket until the client closes the connection or sends a null value.
System.out.println("Received message: " + inputLine); - This line prints the message received from the client to the console.
out.println("Server received: " + inputLine); - This line sends a response message to the client via the output stream of the socket.
The while loop continues to read input from the client, print it to the console, and send responses back to the client until the client closes the connection or sends a null value.
TCP/IP and Datagram Programming:
TCP/IP and datagram programming refers to the use of the TCP/IP protocol suite and datagrams to exchange data between devices on a network.
In Java, the Socket and ServerSocket classes are used for TCP/IP programming,
DatagramSocket and DatagramPacket classes are used for datagram programming.
Example: DatagramSocket:
```java
import java.net.*;
import java.io.*;
public class DatagramSocketExample {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
String message = "Hello, world!";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 1234);
socket.send(packet);
socket.close();
}
}
```
HTTP Protocol and URLs:
The HTTP protocol is a protocol for exchanging data over the web,
URLs are used to identify resources on the web.
In Java, the URL and HttpURLConnection classes are used to implement HTTP-based networked applications.
Example: HttpURLConnection:
```java
import java.net.*;
import java.io.*;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.google.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(content.toString());
}
}
```
I hope this explanation helps you understand the basics of networking in Java!
Chat Program connectionless communication:
import java.io.*;
import java.net.*;
public class ChatProgram {
DatagramSocket socket;
InetAddress address;
BufferedReader in;
byte[] buf;
public ChatProgram() {
try {
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
in = new BufferedReader(new InputStreamReader(System.in));
} catch (IOException e) {
e.printStackTrace();
}
}
public void send() {
try {
String msg = in.readLine();
buf = msg.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
public void receive() {
try {
buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(received);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ChatProgram chat = new ChatProgram();
while (true) {
chat.send();
chat.receive();
}
}
}
This program creates a DatagramSocket object and sets the address to "localhost", representing the local machine.
It then creates a BufferedReader object to read input from the console and a byte array buffer.
The send() method reads a line of text from the console, converts it to bytes, and sends it as a DatagramPacket to the specified address and port (4445 in this case).
The receive() method waits for a DatagramPacket to be received and converts it to a String to be printed to the console.
Finally, the main() method runs an infinite loop that continuously sends and receives messages.
Note:
I. Since this program uses UDP, there is no connection setup or teardown, and messages may be lost or arrive out of order.
II. If you want to ensure reliable transmission, you may want to implement additional error-checking and retransmission mechanisms.
