Sobes.tech
Junior

Which classes handle socket operations in Java?

sobes.tech AI

Answer from AI

Socket and ServerSocket.

  • Socket: Represents a client socket. Used for connecting to a remote host and sending/receiving data.

    // Example of creating a client socket
    try {
        Socket clientSocket = new Socket("localhost", 8080);
        // Further work with input/output streams
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  • ServerSocket: Represents a server socket. Used for listening on a specific port on the local host and accepting incoming client connections.

    // Example of creating a server socket
    try {
        ServerSocket serverSocket = new ServerSocket(8080);
        // Waiting for a client to connect
        Socket clientSocket = serverSocket.accept();
        // Further work with input/output streams
    } catch (IOException e) {
        e.printStackTrace();
    }
    

These classes are in the java.net package.