Java Networking Basics:
- Networking = Exchanging data between devices.
- Java supports networking with java.net package.
- Used for client-server communication.
Important Terms:
- IP Address: Identifies a device (e.g., 192.168.0.1)
- Port Number: Identifies a service (e.g., port 80 = HTTP)
- Together: IP + Port = Full address for communication
Protocols:
- TCP: Reliable, connection-based (used in most cases)
- UDP: Faster, connection-less (for simple messages)
Main Networking Classes:
- InetAddress: Get IP/Hostname
- Socket: For client connections
- ServerSocket: For server side
- URL & URLConnection: For web resources
InetAddress Examples:
- getLocalHost(), getByName("google.com"), getAllByName()
- Methods: getHostName(), getHostAddress()
Socket Programming Basics:
1. Server creates ServerSocket(port)
2. Server calls accept() to wait for connection
3. Client creates Socket(server_IP, port)
4. Connection established, both can send/receive
Streams for Communication:
- Input: getInputStream() -> Read data
- Output: getOutputStream() -> Send data
- Use DataInputStream, DataOutputStream, PrintStream
Socket Close:
Always close:
1. Streams (input/output)
2. Sockets
3. ServerSocket (server side)
Client-Server Example:
Server: Sends 'Hello, Client!'
Client: Connects and reads message
Classes: Socket, ServerSocket, PrintWriter, BufferedReader
DIY Task:
Client sends name to server.
Server replies: 'Hello, [name]! Welcome to the server!'