Networking Basics
Duration: 7 min
This module delves into the fundamental principles of networking in Java, essential for developing robust enterprise applications. Understanding networking is crucial as it enables communication between different systems and devices, forming the backbone of modern software architecture.
Socket Programming
Socket programming is the core of networking in Java, allowing applications to communicate over a network. It involves creating sockets, binding them to an IP address and port, and establishing a connection between a client and a server. This concept is pivotal for building networked applications, from simple chat applications to complex distributed systems.
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("Server started");
Socket socket = serverSocket.accept();
System.out.println("New connection: " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String line;
while ((line = in.readLine())!= null) {
System.out.println("Client says: " + line);
out.writeBytes("Echo: " + line + '\n');
}
socket.close();
serverSocket.close();
}
}Server started
New connection: java.net.Socket@15db9742
Client says: Hello, Server
Datagram Sockets
Datagram sockets are used for sending and receiving UDP packets, which are connectionless and do not guarantee delivery, order, or duplication protection. This method is useful for applications like online games or live broadcasts where speed is more critical than reliability. Understanding datagram sockets is essential for handling real-time data transmission.
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
System.out.println("Waiting for packets");
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + message);
InetAddress address = packet.getAddress();
int port = packet.getPort();
String response = "Hello from UDP Server";
DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.length(), address, port);
socket.send(responsePacket);
socket.close();
}
}💡 Tip: When using datagram sockets, always handle exceptions properly to avoid socket leaks, which can lead to resource exhaustion.
❓ What is the primary use of socket programming in Java?
❓ Which type of socket is used for UDP communication in Java?