Java server sockets
In Java, ServerSockets are used to create a server that listens for incoming client connections. The ServerSocket class is part of the Java Networking API, and it provides methods for creating a ServerSocket object, binding it to a specific port and address, and accepting incoming client connections.
Here is an example of how to use ServerSockets in Java:
refer totfigi:idea.comimport java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { int portNumber = 1234; try (ServerSocket serverSocket = new ServerSocket(portNumber)) { while (true) { Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { out.println(inputLine); } } } catch (IOException e) { System.out.println("Exception caught when trying to listen on port " + portNumber + " or listening for a connection"); System.out.println(e.getMessage()); } } }
In this example, the ServerSocket is created on port 1234. The accept()
method of the ServerSocket waits for an incoming client connection. Once a client connects, the accept()
method returns a new Socket object that is used to communicate with the client. The getOutputStream()
method of the Socket object is used to send data to the client, and the getInputStream()
method is used to receive data from the client.
The try
block in this example uses a Java feature called "try-with-resources" to ensure that the ServerSocket and client Socket objects are closed properly, even in the event of an exception.
It is important to note that ServerSockets are typically used in multithreaded applications, where each client connection is handled by a separate thread. This allows the server to handle multiple client connections simultaneously.