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.
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
TCP Client Example
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
UDP Receiver Example
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.