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
importjava.net.*;importjava.io.*;classTryWithResources{// Use try-with-resources to close a socket.publicstaticvoidmain(Stringargs[])throwsException{intc;// Create a socket connected to internic.net, port 43. Manage this// socket with a try-with-resources block.try(Sockets=newSocket("whois.internic.net",43)){// Obtain input and output streams.InputStreamin=s.getInputStream();OutputStreamout=s.getOutputStream();// Construct a request string.Stringstr=(args.length==0?"MHProfessional.com":args[0])+"\n";// Convert to bytes.bytebuf[]=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.}}