JAVA SOCKET PROGRAMMING
03 June 2025 22:12
Networking
• IP Addresses: Identifying machines on a network.
• Ports: Communication endpoints (e.g., port 80 for HTTP).
• TCP vs UDP:
○ TCP: Reliable, connection-based.
○ UDP: Faster, connectionless.
Networking Basics
IP Addresses
• Unique identifiers assigned to devices on a network.
• IPv4 (e.g., 192.168.1.1) and IPv6 formats.
• Used to route data packets between machines.
Ports
• Numeric endpoints for network communication on a device.
• Range: 0 to 65535 (Ports <1024 are "well-known" or privileged ports).
• Example: Port 80 is used by HTTP servers, Port 443 for HTTPS.
TCP vs UDP
Feature TCP UDP
Connection Connection-oriented (requires handshake) Connectionless (no handshake)
Reliability Reliable delivery, ensures data arrives and in order Unreliable delivery, no guarantee of arrival or order
Speed Slower due to connection setup and error checking Faster due to less overhead
Use cases Web browsing, file transfers, emails Streaming, gaming, VoIP, DNS queries
java.net
java.net is a package in the Java Standard Library that provides classes and interfaces for networking
operations. It contains APIs to work with protocols like TCP/IP and UDP, allowing Java programs to
communicate over a network.
Programmatic Illustration
New Section 1 Page 1
Programmatic Illustration
Step Server Client
Start program Create ServerSocket to listen on port 5000 Create Socket to connect to server
Wait/connect accept() blocks until client connects Connects to server on localhost:5000
Exchange data Read line from client, print message Send line "Hello from client!"
Send line "Hello from server!" Read server response
Close connection Close client socket Close socket
New Section 1 Page 2