Java Network Programming
Network programming allows computers to communicate with each other over a network. Java provides the powerful java.net package, enabling developers to easily create network applications, whether based on TCP or UDP protocols.
Network Basics
- IP Address: A unique identifier for each computer on a network. Java uses the
InetAddressclass to represent IP addresses. - Port: A 16-bit number (0-65535) used to identify a specific application or service on a computer. An IP address combined with a port number can uniquely identify a process on the network.
- Socket: An endpoint for network communication. Two applications establish a connection through a pair of sockets (containing IP addresses and ports) to exchange data.
InetAddress Class
The InetAddress class is used to represent IP addresses. It has no public constructor and can only be created through static methods.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample {
public static void main(String[] args) {
try {
// Get the address of the local host
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local hostname: " + localHost.getHostName());
System.out.println("Local IP address: " + localHost.getHostAddress());
// Get address by domain name
InetAddress googleHost = InetAddress.getByName("www.google.com");
System.out.println("\nGoogle hostname: " + googleHost.getHostName());
System.out.println("Google IP address: " + googleHost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}TCP Programming
TCP (Transmission Control Protocol) is a connection-oriented, reliable protocol. Both parties need to establish a connection before data transmission, similar to making a phone call.
ServerSocket: Used on the server side to listen on a specified port and wait for client connection requests.Socket: Used on the client or server side, representing one end of a network connection.
TCP Server Example
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) throws IOException {
// 1. Create a ServerSocket, listening on port 8080
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started, waiting for client connection...");
// 2. Call accept() method, blocking until a client connects
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
// 3. Get output stream, send data to client
OutputStream os = clientSocket.getOutputStream();
os.write("Hello, Client! You are connected.".getBytes());
os.flush();
// 4. Close resources
os.close();
clientSocket.close();
serverSocket.close();
}
}TCP Client Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) throws IOException {
// 1. Create a Socket, connect to the server's IP and port
Socket socket = new Socket("127.0.0.1", 8080);
System.out.println("Connected to server.");
// 2. Get input stream, read data sent by the server
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverMessage = br.readLine();
System.out.println("Received message from server: " + serverMessage);
// 3. Close resources
br.close();
socket.close();
}
}UDP Programming
UDP (User Datagram Protocol) is a connectionless, unreliable protocol. It does not require establishing a connection and directly sends data packets (Datagrams) to the target address. It's fast but may lose packets, similar to sending letters.
DatagramSocket: Used to send and receive datagram packets.DatagramPacket: Used to encapsulate data to be sent or received.
UDP Sender Example
import java.io.IOException;
import java.net.*;
public class UdpSender {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
String message = "Hello, UDP Receiver!";
byte[] data = message.getBytes();
InetAddress receiverAddress = InetAddress.getByName("127.0.0.1");
int receiverPort = 9090;
// Create data packet
DatagramPacket packet = new DatagramPacket(data, data.length, receiverAddress, receiverPort);
// Send data packet
socket.send(packet);
System.out.println("Message sent.");
socket.close();
}
}UDP Receiver Example
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiver {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[1024];
// Create receiving data packet
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Receive data (blocking)
socket.receive(packet);
String receivedMessage = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received message: " + receivedMessage);
socket.close();
}
}URL Programming
Java also provides high-level APIs for handling URLs, making it easy to access web resources.
URL: Represents a Uniform Resource Locator.URLConnection: Can be used to read and write resources pointed to by a URL.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class UrlExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
// Read webpage content
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}