import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(1234); System.out.println("Server listening on port 1234"); while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("Client " + clientSocket.getInetAddress() + " connected"); // handle client connection clientSocket.close(); } } }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(1234); System.out.println("Server listening on port 1234"); while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("Client " + clientSocket.getInetAddress() + " connected"); // start a new thread to handle client connection new Thread(() -> { // handle client connection try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } }).start(); } } }This example sets up a multi-threaded server that listens for incoming connections on port 1234. Once a client connects, the server spins off a new thread to handle the client connection. This allows multiple clients to connect to the server simultaneously without blocking on each other. In summary, the java.net package library contains the ServerSocket class, which is used to create a server-side socket that listens for incoming connection requests from clients. We demonstrated two examples of how you might use ServerSocket in Java, one for a basic server setup and another for a multi-threaded server setup.