Skip to content

Socket Programming

  • Java Socket Programming is used for communication between the application running on different machine.
  • Java Socket Programming support :
Connection Oriented Connection-Less
Classes Used : Classes Used :
1. Socket 1. DatagramSocket
2. ServerSocket 2. DatagramPacket

Client in socket programming must know : - IP Adress

Socket Class ServerSocket Class
This method is used to create a socket. This class is used to create a ServerSocket.
Methods Methods
- public InputStream getInputStream() - public Socket accept()
- public OutputStream getOutputStream() - public synchronized void close()
- public synchronized void close()

Implementation

import java.net.*;
import java.io.*;

class TryWithResources {
    // Use try-with-resources to close a socket.
    public static void main(String args[]) throws Exception {
        int c;
        // Create a socket connected to internic.net, port 43. Manage this
        // socket with a try-with-resources block.
        try (Socket s = new Socket("whois.internic.net", 43)) {
            // Obtain input and output streams.
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            // Construct a request string.
            String str = (args.length == 0 ? "MHProfessional.com" : args[0]) + "\n";
            // Convert to bytes.
            byte buf[] = str.getBytes();
            // Send request.
            out.write(buf);
            // Read and display response.
            while ((c = in.read()) != -1) {
                System.out.print((char) c);
            }
        }
        // The socket is now closed.
    }
}