9.2.1 Socket Class Explained
The Socket
class in Java is a fundamental component for network communication, enabling two applications running on different machines to communicate over a network. Understanding the Socket
class is essential for building client-server applications in Java.
Key Concepts
1. Socket Creation
A Socket
is created using the constructor that takes the server's IP address and port number as parameters. This establishes a connection to the server.
Example
Socket socket = new Socket("localhost", 12345);
2. Socket Communication
Once a connection is established, data can be sent and received using input and output streams. The getInputStream()
and getOutputStream()
methods of the Socket
class are used to obtain these streams.
Example
InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream();
3. Socket Closing
After communication is complete, it is important to close the socket to free up resources. This is done using the close()
method.
Example
socket.close();
4. ServerSocket Class
The ServerSocket
class is used on the server side to listen for incoming client connections. The accept()
method blocks until a client connects, returning a Socket
object for communication with the client.
Example
ServerSocket serverSocket = new ServerSocket(12345); Socket clientSocket = serverSocket.accept();
Examples and Analogies
Think of a Socket
as a telephone line that connects two people. The Socket
class is like the phone that establishes the connection, allowing the two people to talk. The input and output streams are like the ears and mouth, enabling the exchange of information.
The ServerSocket
class is like a receptionist at a company who waits for incoming calls. When a call comes in, the receptionist hands the phone to the appropriate person, establishing a direct line of communication.
By mastering the Socket
class, you can create robust client-server applications that communicate effectively over a network, ensuring seamless data exchange between different machines.