Java Networking Basics
Introduction to Networking Concepts in Java
Mrs. R. Nancy Beaulah MCA., M.Phil., SET.,NET.,
Assistant Professor,
Department of Computer Applications
V.V.Vanniaperumal College for Women,
Virudhunagar.
Introduction to Networking
• What is Networking?
• Communication between devices
• Importance in distributed systems
• Key Concepts:
• IP Address
• Port
• Protocols (TCP/IP, UDP)
Java Networking API Overview
• Key Classes in java.net.Package
• InetAddress
• SocketServer
• Socket
• URL
• URLConnection
• DatagramSocket
InetAddress Class
•Purpose:
•Represents an IP address.
•Methods:
•getByName(String host)
•getLocalHost()
•Example:
InetAddress address = InetAddress.getByName
("www.example.com");
System.out.println(address);
Socket and ServerSocket Classes
• Socket:
• Represents a client-side socket.
• Socket(String host, int port)
• ServerSocket:
• Listens for incoming connections.
• ServerSocket(int port)
Example:
// Server
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
// Client
Socket socket = new Socket("localhost", 8080);
Creating a Simple Client-Server Application
• Server Code:
• Accepts connections, reads data.
• Client Code:
• Connects to server, sends data.
• Code Snippets:
• Include small code snippets for Server and Client.
TCP vs. UDP
•TCP:
•Connection-oriented, reliable, ordered.
•Classes: Socket, ServerSocket
•UDP:
•Connectionless, faster, less reliable.
•Classes: DatagramSocket, DatagramPacket
Datagram (UDP) Sockets
• DatagramSocket:
• Sends/receives packets without establishing a
connection.
• Example
DatagramSocket socket = new DatagramSocket();
byte[] buffer = "Hello".getBytes();
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length, address, port);
socket.send(packet);
Handling Networking Exceptions
•Common Exceptions:
•UnknownHostException
•SocketException
•IOException
•Best Practices:
•Proper error handling
•Use try-catch blocks