ADVANCED
JAVA
TOPIC
• NETWORK BASICS
• URL
• SOCKET OVERVIEW
• TCP/IP CLIENT SOCKETS
• TCP/IP SERVER SOCKETS
NETWORK BASICS
◦ Prior to the creation of applications using the java.net.package , you must first
understand some basic concepts of networking. Some of the basic concepts of
networking are as follows :
 TCP/IP suite
 UDP
 Port
 URL
TCP/IP SUIT
◦ A majority of the internet uses a protocol suite
called the Internet Protocol Suite also known as
the TCP/IP protocol suite. This suite is a
combination of protocols which encompasses a
number of different protocols for different
purpose and need. Because the two major
protocols in this suites are TCP (Transmission
Control Protocol) and IP (Internet Protocol),
this is commonly termed as TCP/IP Protocol
suite. This protocol suite has its own reference
model which it follows over the internet. In
contrast with the OSI model, this model of
protocols contains less layers.
◦ This model is indifferent to the actual hardware implementation, i.e. the physical layer of OSI Model.
This is why this model can be implemented on almost all underlying technologies. Transport and
Internet layers correspond to the same peer layers. All three top layers of OSI Model are compressed
together in single Application layer of TCP/IP Model.
UDP
• UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be
transmitted between applications.
• It is mostly utilized to transfer images, audio and video files over a network in many application.
• If some bits are lost during transfer of images, audio or video files over a network, the new image, audio
or video file can be created with negligible minor variation.
• It is also used in query-response type applications. One of the known applications using UDP is DNS to
resolve to names to IP addresses.
PORT
◦ The port is 16-bit number which is used to uniquely identify different applications. It acts as a communication
endpoint between applications. The port number is associated with the IP address for communication between
two applications.
◦ IP address identifies the machine, whereas port number identifies the process on that machine. A distinct port
number is used for every new process from the range 0 to 65535 out of which first initial port numbers (upto
1023) are reserved for well-known applications.
13 Specifies the data and time services.
21 Denotes FTP which transmits file.
23 Represent Telnet that allow remote login
25 Specifies SMTP that is mainly used for sending mails.
67 BOOTP that helps in configuration during the boot
time
80 HTTP is used for transferring web pages.
109 POP that accesses mail boxes.
URL
What is a URL?
◦ As you must be knowing that Uniform Resource Locator-URL is a string of text that identifies all the resources
on Internet, telling us the address of the resource, how to communicate with it and retrieve something from it.
A Simple URL looks like:
http://www.gtu.ac.in/result.aspx/
protocol host machine file name
Components of a URL:-
◦ Protocol: HTTP is the protocol here
◦ Hostname: Name of the machine on which the resource lives.
◦ File Name: The path name to the file on the machine.
◦ Port Number: Port number to which to connect (typically optional).
EXAMPLE
◦ import java.net.*;
◦ import java.io.*;
◦ public class URLDemo {
◦ public static void main(String [] args) {
◦ try {
◦ URL url = new URL("https://www.amrood.com/index.htm?language=en#j2se");
◦
◦ System.out.println("URL is " + url.toString());
◦ System.out.println("protocol is " + url.getProtocol());
◦ System.out.println("authority is " + url.getAuthority());
◦ System.out.println("file name is " + url.getFile());
◦ System.out.println("host is " + url.getHost());
◦ System.out.println("path is " + url.getPath());
◦ System.out.println("port is " + url.getPort());
◦ System.out.println("default port is " +
url.getDefaultPort());
◦ System.out.println("query is " +
url.getQuery());
◦ System.out.println("ref is " + url.getRef());
◦ } catch (IOException e) {
◦ e.printStackTrace();
◦ }
◦ }
◦ }
OUTPUT :
◦ URL is
https://www.amrood.com/index.htm?language=en#j2
se
◦ protocol is http
◦ authority is www.amrood.com
◦ file name is /index.htm?language=en
◦ host is www.amrood.com
◦ path is /index.htm
◦ port is -1
◦ default port is 80
◦ query is language=en
◦ ref is j2se
SOCKET OVERVIEW
◦ The server is just like any ordinary program running on a computer. Each computer is equipped with some
ports. The server connects to one of the ports. This process is called Binding to a port.
The client in socket programming must know two information:
IP Address of Server, and
Port number.
◦ Here, we are going to make one-way client and server communication. In this application, client sends a
message to the server, server reads the message and prints it. Here, two classes are being used: Socket and
ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and
write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks
the console until the client is connected. After the successful connection of client, it returns the instance of
Socket at server-side.
Creating Server:
◦ To create the server application, we need to create the instance of ServerSocket class. Here, we are
using 6666 port number for the communication between the client and server. You may also choose
any other port number. The accept() method waits for the client. If clients connects with the given
port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:
◦ To create the client application, we need to create the instance of Socket class. Here, we need to pass
the IP address or hostname of the Server and a port number. Here, we are using "localhost" because
our server is running on same system.
Socket s=new Socket("localhost",6666);
TCP/IP CLIENT SOCKETS
◦ TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between
hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local
machine or on any other machine on the Internet.
◦ There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The ServerSocket class is designed
to be a "listener," which waits for clients to connect before doing anything. Thus, ServerSocket is for servers. The Socket class
is for clients. It is designed to connect to server sockets and initiate protocol exchanges. Because client sockets are the most
commonly used by Java applications, they are examined here.
◦ The creation of a Socket object implicitly establishes a connection between the client and server. There are no methods or
constructors that explicitly expose the details of establishing that connection. Here are two constructors used to create client
sockets:
◦ Socket defines several instance methods. For example, a Socket can be examined at any time for the address and port information
associated with it, by use of the following methods:
◦ InetAddress getInetAddress( ) : Returns the InetAddress associated with the Socket object. It returns null if the socket is not
connected.
◦ int getPort( ) : Returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not
connected.
◦ int getLocalPort( ) : Returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound.
◦ InputStream getInputStream( ) throws IOException : Returns the InputStream associated with the invoking socket.
◦ OutputStream getOutputStream( )throws IOException : Returns the OutputStream associated with the invoking socket.
EXAMPLE :
◦ import java.net.*;
◦ import java.io.*;
◦ public class TimeClient {
◦ public static void main(String[] args) {
◦ String hostname = "time.nist.gov";
◦ int port = 13;
◦ try (Socket socket = new Socket(hostname, port)) {
◦ InputStream input = socket.getInputStream();
◦ InputStreamReader reader = new InputStreamReader(input);
◦ int character;
◦ StringBuilder data = new StringBuilder();
◦ while ((character = reader.read()) != -1) {
◦ data.append((char) character);
◦ }
◦ System.out.println(data);
◦ } catch (UnknownHostException ex) {
◦ System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
◦ System.out.println("I/O error: " + ex.getMessage());
◦ }
◦ } }
TCP/IP SERVER SOCKETS
◦ As mentioned earlier, Java has a different socket
class that must be used for creating server
applications. The ServerSocket class is used to
create servers that listen for either local or remote
client programs to connect to them on published
ports. ServerSockets are quite different from
normal Sockets. When you create
a ServerSocket, it will register itself with the
system as having an interest in client connections.
The constructors for ServerSocket reflect the
port number that you want to accept connections
on and, optionally, how long you want the queue
for said port to be. The queue length tells the
system how many client connections it can leave
pending before it should simply refuse
connections. The default is 50. The constructors
might throw an IOException under adverse
conditions. Here are three of its constructors:
EXAMPLE
◦ import java.io.*;
◦ import java.net.*;
◦ import java.util.Date;
public class TimeServer {
◦ public static void main(String[] args) {
◦ if (args.length < 1) return;
◦ int port = Integer.parseInt(args[0]);
◦ try (ServerSocket serverSocket = new
ServerSocket(port)) {
System.out.println("Server is listening on
port " + port);
◦ while (true) {
◦ Socket socket = serverSocket.accept();
◦
◦ System.out.println("New client connected");
◦
◦ OutputStream output = socket.getOutputStream();
◦ PrintWriter writer = new PrintWriter(output, true);
◦
◦ writer.println(new Date().toString());
◦ }
◦
◦ } catch (IOException ex) {
◦ System.out.println("Server exception: " + ex.getMessage());
◦ ex.printStackTrace();
◦ }}}
A.java

A.java

  • 1.
  • 2.
    TOPIC • NETWORK BASICS •URL • SOCKET OVERVIEW • TCP/IP CLIENT SOCKETS • TCP/IP SERVER SOCKETS
  • 3.
    NETWORK BASICS ◦ Priorto the creation of applications using the java.net.package , you must first understand some basic concepts of networking. Some of the basic concepts of networking are as follows :  TCP/IP suite  UDP  Port  URL
  • 4.
    TCP/IP SUIT ◦ Amajority of the internet uses a protocol suite called the Internet Protocol Suite also known as the TCP/IP protocol suite. This suite is a combination of protocols which encompasses a number of different protocols for different purpose and need. Because the two major protocols in this suites are TCP (Transmission Control Protocol) and IP (Internet Protocol), this is commonly termed as TCP/IP Protocol suite. This protocol suite has its own reference model which it follows over the internet. In contrast with the OSI model, this model of protocols contains less layers.
  • 5.
    ◦ This modelis indifferent to the actual hardware implementation, i.e. the physical layer of OSI Model. This is why this model can be implemented on almost all underlying technologies. Transport and Internet layers correspond to the same peer layers. All three top layers of OSI Model are compressed together in single Application layer of TCP/IP Model. UDP • UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. • It is mostly utilized to transfer images, audio and video files over a network in many application. • If some bits are lost during transfer of images, audio or video files over a network, the new image, audio or video file can be created with negligible minor variation. • It is also used in query-response type applications. One of the known applications using UDP is DNS to resolve to names to IP addresses.
  • 6.
    PORT ◦ The portis 16-bit number which is used to uniquely identify different applications. It acts as a communication endpoint between applications. The port number is associated with the IP address for communication between two applications. ◦ IP address identifies the machine, whereas port number identifies the process on that machine. A distinct port number is used for every new process from the range 0 to 65535 out of which first initial port numbers (upto 1023) are reserved for well-known applications. 13 Specifies the data and time services. 21 Denotes FTP which transmits file. 23 Represent Telnet that allow remote login 25 Specifies SMTP that is mainly used for sending mails. 67 BOOTP that helps in configuration during the boot time 80 HTTP is used for transferring web pages. 109 POP that accesses mail boxes.
  • 7.
    URL What is aURL? ◦ As you must be knowing that Uniform Resource Locator-URL is a string of text that identifies all the resources on Internet, telling us the address of the resource, how to communicate with it and retrieve something from it. A Simple URL looks like: http://www.gtu.ac.in/result.aspx/ protocol host machine file name Components of a URL:- ◦ Protocol: HTTP is the protocol here ◦ Hostname: Name of the machine on which the resource lives. ◦ File Name: The path name to the file on the machine. ◦ Port Number: Port number to which to connect (typically optional).
  • 8.
    EXAMPLE ◦ import java.net.*; ◦import java.io.*; ◦ public class URLDemo { ◦ public static void main(String [] args) { ◦ try { ◦ URL url = new URL("https://www.amrood.com/index.htm?language=en#j2se"); ◦ ◦ System.out.println("URL is " + url.toString()); ◦ System.out.println("protocol is " + url.getProtocol()); ◦ System.out.println("authority is " + url.getAuthority()); ◦ System.out.println("file name is " + url.getFile()); ◦ System.out.println("host is " + url.getHost());
  • 9.
    ◦ System.out.println("path is" + url.getPath()); ◦ System.out.println("port is " + url.getPort()); ◦ System.out.println("default port is " + url.getDefaultPort()); ◦ System.out.println("query is " + url.getQuery()); ◦ System.out.println("ref is " + url.getRef()); ◦ } catch (IOException e) { ◦ e.printStackTrace(); ◦ } ◦ } ◦ } OUTPUT : ◦ URL is https://www.amrood.com/index.htm?language=en#j2 se ◦ protocol is http ◦ authority is www.amrood.com ◦ file name is /index.htm?language=en ◦ host is www.amrood.com ◦ path is /index.htm ◦ port is -1 ◦ default port is 80 ◦ query is language=en ◦ ref is j2se
  • 10.
    SOCKET OVERVIEW ◦ Theserver is just like any ordinary program running on a computer. Each computer is equipped with some ports. The server connects to one of the ports. This process is called Binding to a port. The client in socket programming must know two information: IP Address of Server, and Port number. ◦ Here, we are going to make one-way client and server communication. In this application, client sends a message to the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it returns the instance of Socket at server-side.
  • 12.
    Creating Server: ◦ Tocreate the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port number for the communication between the client and server. You may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket. ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection and waits for the client Creating Client: ◦ To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same system. Socket s=new Socket("localhost",6666);
  • 13.
    TCP/IP CLIENT SOCKETS ◦TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. ◦ There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The ServerSocket class is designed to be a "listener," which waits for clients to connect before doing anything. Thus, ServerSocket is for servers. The Socket class is for clients. It is designed to connect to server sockets and initiate protocol exchanges. Because client sockets are the most commonly used by Java applications, they are examined here. ◦ The creation of a Socket object implicitly establishes a connection between the client and server. There are no methods or constructors that explicitly expose the details of establishing that connection. Here are two constructors used to create client sockets:
  • 14.
    ◦ Socket definesseveral instance methods. For example, a Socket can be examined at any time for the address and port information associated with it, by use of the following methods: ◦ InetAddress getInetAddress( ) : Returns the InetAddress associated with the Socket object. It returns null if the socket is not connected. ◦ int getPort( ) : Returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected. ◦ int getLocalPort( ) : Returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound. ◦ InputStream getInputStream( ) throws IOException : Returns the InputStream associated with the invoking socket. ◦ OutputStream getOutputStream( )throws IOException : Returns the OutputStream associated with the invoking socket. EXAMPLE : ◦ import java.net.*; ◦ import java.io.*; ◦ public class TimeClient { ◦ public static void main(String[] args) { ◦ String hostname = "time.nist.gov"; ◦ int port = 13;
  • 15.
    ◦ try (Socketsocket = new Socket(hostname, port)) { ◦ InputStream input = socket.getInputStream(); ◦ InputStreamReader reader = new InputStreamReader(input); ◦ int character; ◦ StringBuilder data = new StringBuilder(); ◦ while ((character = reader.read()) != -1) { ◦ data.append((char) character); ◦ } ◦ System.out.println(data); ◦ } catch (UnknownHostException ex) { ◦ System.out.println("Server not found: " + ex.getMessage()); } catch (IOException ex) { ◦ System.out.println("I/O error: " + ex.getMessage()); ◦ } ◦ } }
  • 16.
    TCP/IP SERVER SOCKETS ◦As mentioned earlier, Java has a different socket class that must be used for creating server applications. The ServerSocket class is used to create servers that listen for either local or remote client programs to connect to them on published ports. ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will register itself with the system as having an interest in client connections. The constructors for ServerSocket reflect the port number that you want to accept connections on and, optionally, how long you want the queue for said port to be. The queue length tells the system how many client connections it can leave pending before it should simply refuse connections. The default is 50. The constructors might throw an IOException under adverse conditions. Here are three of its constructors:
  • 17.
    EXAMPLE ◦ import java.io.*; ◦import java.net.*; ◦ import java.util.Date; public class TimeServer { ◦ public static void main(String[] args) { ◦ if (args.length < 1) return; ◦ int port = Integer.parseInt(args[0]); ◦ try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server is listening on port " + port);
  • 18.
    ◦ while (true){ ◦ Socket socket = serverSocket.accept(); ◦ ◦ System.out.println("New client connected"); ◦ ◦ OutputStream output = socket.getOutputStream(); ◦ PrintWriter writer = new PrintWriter(output, true); ◦ ◦ writer.println(new Date().toString()); ◦ } ◦ ◦ } catch (IOException ex) { ◦ System.out.println("Server exception: " + ex.getMessage()); ◦ ex.printStackTrace(); ◦ }}}