0% found this document useful (0 votes)
5 views

Networking in Java(2)

Uploaded by

berihufsaha12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Networking in Java(2)

Uploaded by

berihufsaha12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter-6: Networking in java

In Java, networking is primarily handled through the java.net package, which provides classes
for networking operations. Key classes include Socket and ServerSocket for TCP/IP-based
communication, DatagramSocket and DatagramPacket for UDP-based communication, and URL
for URL handling. You can use these classes to create client-server applications, establish
connections, send and receive data over networks, and more.

Networking overview

Sure, here's a brief overview of networking in Java:

1. Java.net Package: Java's networking capabilities are provided by the java.net package. This
package contains classes and interfaces for networking operations, such as connecting to servers,
sending and receiving data, and handling network protocols.

2. Client-Server Model: Java allows you to create both client and server applications. In a client-
server model, the server provides services, and clients connect to the server to access these
services.

3. TCP/IP and UDP Protocols: Java supports both TCP/IP and UDP protocols for
communication. TCP (Transmission Control Protocol) provides reliable, connection-oriented
communication, while UDP (User Datagram Protocol) provides fast, connectionless
communication.

4. Socket Programming: The Socket and ServerSocket classes are used for TCP-based
communication. A Socket represents an endpoint for communication between two machines,
while a ServerSocket waits for client connections.

5. Datagram Programming: For UDP-based communication, Java provides the DatagramSocket


and DatagramPacket classes. DatagramSocket represents a UDP socket, while DatagramPacket
represents a packet of data to be sent or received.

6. URL Handling: Java's URL class allows you to work with URLs (Uniform Resource
Locators), such as opening connections to remote resources over the network.

7. Concurrency: Networking in Java often involves concurrent programming to handle multiple


client connections simultaneously. Java's Thread class and concurrency utilities such as
ExecutorService can be used to manage concurrent network operations efficiently.

8. Security: Java provides built-in support for secure communication over networks through
protocols such as SSL/TLS. The javax.net.ssl package contains classes and interfaces for
SSL/TLS-based communication. Overall, Java's networking capabilities allow you to build
robust client-server applications that can communicate over networks using various protocols.
Types of connections
In Java, there are primarily two types of network connections:

1. TCP/IP Connections: TCP (Transmission Control Protocol) is a reliable, connection-oriented


protocol used for communication between applications over a network.

In Java, TCP/IP connections are typically established using the Socket and ServerSocket classes
from the java.net package.

Socket: Represents an endpoint for communication between two machines. It can be used to
create client-side connections.

Server Socket: Listens for incoming connections from clients and creates a new Socket for each
client connection.

2. UDP Connections: UDP (User Datagram Protocol) is a connectionless protocol that provides
fast, unreliable communication between applications. In Java, UDP connections are handled
using the DatagramSocket and DatagramPacket classes from the java.net package.

DatagramSocket: Represents a UDP socket that can send and receive datagrams (packets) over a
network.

DatagramPacket: Represents a packet of data to be sent or received. It contains information such


as the data payload, destination address, and port number. These two types of connections offer
different trade-offs in terms of reliability, performance, and overhead. TCP/IP connections
guarantee data delivery and ordering but may introduce higher latency and overhead due to
connection setup and management.

UDP connections, on the other hand, provide low-latency communication but do not guarantee
delivery or ordering of packets. In Java, you can choose the appropriate type of network
connection based on the requirements of your application, such as reliability, latency sensitivity,
and network conditions.

Examples

Sure, here are two basic examples of networking in Java:TCP/IP Client-Server

Example: This example demonstrates how to create a simple TCP/IP client-server application in
Java.

// Server.java

import java.io.*;

import java.net.*;
public class Server {

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

ServerSocket serverSocket = new ServerSocket(8888); // Create server socket

System.out.println("Server is running and waiting for connections...");

Socket clientSocket = serverSocket.accept(); // Accept client connection

System.out.println("Client connected: " + clientSocket);

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

String message = in.readLine(); // Read message from client

System.out.println("Message from client: " + message);

out.println("Message received!"); // Send response to client

clientSocket.close(); // Close client connection

serverSocket.close(); // Close server socket

Client
// Client.java

import java.io.*;

import java.net.*;

public class Client {

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

Socket socket = new Socket("localhost", 8888); // Connect to server

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


out.println("Hello, Server!"); // Send message to server

String response = in.readLine(); // Receive response from server

System.out.println("Response from server: " + response);

socket.close(); // Close socket

UDP Example: This example demonstrates how to create a simple UDP client-server application
in Java.

// UDPServer.java
import java.net.*;

public class UDPServer {

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

DatagramSocket serverSocket = new DatagramSocket(9876); // Create server socket

byte[] receiveData = new byte[1024];

System.out.println("Server is running and waiting for packets...");

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

serverSocket.receive(receivePacket); // Receive packet from client

String message = new String(receivePacket.getData()).trim();

System.out.println("Message from client: " + message);

InetAddress IPAddress = receivePacket.getAddress();

int port = receivePacket.getPort();

byte[] sendData = "Message received!".getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,


port);

serverSocket.send(sendPacket); // Send response to client

serverSocket.close(); // Close server socket


}

UDP client
// UDPClient.java

import java.net.*;

public class UDPClient {

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

DatagramSocket clientSocket = new DatagramSocket();

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

byte[] sendData = "Hello, Server!".getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,


9876);

clientSocket.send(sendPacket); // Send packet to server

byte[] receiveData = new byte[1024];

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

clientSocket.receive(receivePacket); // Receive response from server

String response = new String(receivePacket.getData()).trim();

System.out.println("Response from server: " + response);

clientSocket.close(); // Close client socket

These examples demonstrate basic client-server communication using TCP/IP and UDP protocol

Socket Programming

Socket programming in java allows communication between two nodes on a network. You can
create both client and server applications using java s java.net package.
Create simple client-server application where the client sends messages to the server, and the
server echoes the messages back to the client?

You might also like