Using Socket
and ServerSocket
in Java is quite straightforward for creating TCP-based communications. Below is an explanation describing how to use these classes, along with sample code to implement a basic client-server communication.
Key Classes
ServerSocket
- Used by the server to listen for incoming client connections on a specific port.
Socket
- Used by both the client and server to establish a connection and perform data exchange.
Example TCP Communication
Here is an example where the server waits for incoming connections and the client connects to the server, sending and receiving messages.
1. Creating the Server
The server uses ServerSocket
to listen on a specific port and accepts client connections using the accept()
method. Once a connection is accepted, it creates a Socket
instance to facilitate communication with the client.
package org.kodejava.net;
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) {
int port = 1234; // Port to listen on
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
// Accepts an incoming connection from a client
Socket socket = serverSocket.accept();
System.out.println("New client connected");
// Create input and output streams for communication
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
// Read data sent by the client
String text;
while ((text = reader.readLine()) != null) {
System.out.println("Received: " + text);
// Send a response
writer.println("Server: " + text);
// Break communication loop if client sends "bye"
if (text.equalsIgnoreCase("bye")) {
System.out.println("Client disconnected");
break;
}
}
// Close the socket
socket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
2. Creating the Client
The client uses a Socket
to connect to the server’s IP address and port. Once connected, the client uses input and output streams for communication.
package org.kodejava.net;
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) {
String hostname = "localhost"; // Server's hostname or IP
int port = 1234; // Server's port
try (Socket socket = new Socket(hostname, port)) {
// Input and output streams for communication
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
// Send messages to the server
Console console = System.console();
String text;
while (true) {
text = console.readLine("Enter message: ");
writer.println(text);
// Read the server's response
String response = reader.readLine();
System.out.println(response);
// Exit loop if "bye" is sent
if (text.equalsIgnoreCase("bye")) {
break;
}
}
} catch (UnknownHostException ex) {
System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}
How It Works
- Server Execution:
- Run the
TCPServer
program first. It creates a server socket that listens on port 1234. - When a client connects, the server accepts the connection and establishes communication.
- Run the
- Client Execution:
- Run the
TCPClient
program after the server is running. - The client connects to the server (specified as
localhost
with port1234
). - You can type a message in the client that is sent to the server, and the server responds.
- Run the
- End Communication:
- Typing “bye” in the client console ends the communication.
Output Example
Server:
Server is listening on port 1234
New client connected
Received: Hello Server
Received: How are you?
Received: bye
Client disconnected
Client:
Enter message: Hello Server
Server: Hello Server
Enter message: How are you?
Server: How are you?
Enter message: bye
Server: bye
Notes:
- Always make sure to handle exceptions properly, as network communication is prone to failures.
- Close resources (e.g., sockets and streams) appropriately to prevent resource leakage.
- You can enhance this basic example with features like multithreading to handle multiple clients on the server side.