Welcome to our Java ServerSocket tutorial! In this lesson, we'll dive into creating a server using the ServerSocket class in Java. This will allow us to establish communication between two devices over a network. Let's get started! š
The ServerSocket class is used to create a server that waits for incoming connections. It's an essential part of building networked applications in Java.
import java.net.ServerSocket;
import java.net.Socket;Let's create a simple server that listens for incoming client connections and sends a response back.
public class Server {
private ServerSocket serverSocket;
public void start(int port) throws IOException {
serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New connection from " + clientSocket.getInetAddress().getHostAddress());
handleRequest(clientSocket);
}
}
public void handleRequest(Socket socket) {
// Handle the request from the client here
}
public static void main(String[] args) throws IOException {
int port = 8080;
Server server = new Server();
server.start(port);
}
}š” Pro Tip: Save this code in a file named Server.java and compile it using javac Server.java. Run it using java Server.
Now, let's modify our handleRequest() method to send a response back to the client.
public class Server {
// ...
public void handleRequest(Socket socket) {
PrintWriter out;
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process the request here
out.println("Hello from the server!");
}
} catch (IOException e) {
System.err.println("Error handling request: " + e.getMessage());
}
}
// ...
}Next, let's create a simple client that connects to our server and sends a request.
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Client {
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 8080;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
System.out.println("Connected to server");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello from the client!");
String response = in.readLine();
System.out.println("Server response: " + response);
socket.close();
}
}š” Pro Tip: Save this code in a file named Client.java and compile it using javac Client.java. Run it using java Client.
What is the purpose of the `ServerSocket` class in Java?
That's it for today! In the next lesson, we'll dive deeper into handling client requests and explore more advanced topics in Java ServerSocket programming. Keep learning and coding! š¤š»š