Chapter-4 Network Programming: Client-Server Architecture
Chapter-4 Network Programming: Client-Server Architecture
Network programming
1. What is Network?
2. Client-Server Architecture
Server: - an application that runs on the host computer that provides a means of
connection and Useful information once a connection is established.
Client: - application(s) running on different computer(s) that seek to establish a
connection and request computation/ information from the server.
3. What is a Socket?
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network. Network
programming fall into two categories: - the sockets API and tools for working with Uniform
Resource Locators (URLs).
A socket is a communication end point. Sockets are popularly used in client/server
computing. Socket is a door between application process and end-to-end-transport protocol. A
socket on one computer can “talk” to a socket on another computer via communication channel.
Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level routing
protocol that breaks data into small packets and sends them to an address across a network. Java
support two protocols:-
Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly
string together these packets, sorting and retransmitting them as necessary to reliably
transmit data. TCP is used for reliable stream-based I/O across the network.
User Datagram Protocol (UDP) can be used directly to support fast, connectionless,
unreliable transport of packets. UDP supports a simpler, point-to-point datagram-oriented
model.
Java provides a set of classes, defined in a package called java.net, to enable the rapid
development of network applications. Key classes, interfaces, and exceptions in java.net package
are:-
The Classes
ContentHandler DatagramPacket
DatagramSocket ContentHandlerFactory
DatagramSocketImpl FileNameMap
HttpURLConnection SocketImplFactory
InetAddress URLStreamHandlerFactory
MulticastSocket Exceptions
ServerSocket BindException
Socket ConnectException
SocketImpl MalformedURLException
URL NoRouteToHostException
URLConnection ProtocolException
URLEncoder SocketException
URLStreamHandler UnknownHostException
The Interfaces UnknownServiceException
InetAddress
The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address. You interact with this class by using the name of an IP host,
which is more convenient and understandable than its IP address. The InetAddress class hides
the number inside. InetAddress can handle both IPv4 and IPv6 addresses.
Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress object, you have to
use one of the available factory methods. Factory methods are merely a convention
whereby static methods in a class return an instance of that class. Three commonly used
InetAddress factory methods are shown here:-
import java.net.*;
class InetAddressTest
System.out.println(Address);
Address = InetAddress.getByName("www.HerbSchildt.com");
System.out.println(Address);
System.out.println(SW[i]);
}}
Output
default/166.203.115.212
www.HerbSchildt.com/216.92.65.4
www.nba.com/216.66.31.161
www.nba.com/216.66.31.179
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e){System.out.println(e);}
} }
Output:
5. TCP Sockets
TCP is a reliable point-to-point communication protocol that client-server applications on the
Internet use to communicate with each other. To communicate over TCP, a client program and a
server program establish a connection to one another. The client and server programs both bind a
socket to each end of the connection and communicate by reading and writing to those
sockets. There are some commonly used socket classes in the java.net packages.
Java uses Socket for clients and ServerSocket for servers in a connection-oriented
environment.
Server Sockets: - To create Server sockets java uses ServerSocket class. This class has the
following constructors:
Methods Description
Returns the port that the server socket is listening on. This method is useful if
you passed in 0 as the port number in a constructor and let the server find a
port for you.
Client Sockets: -To create client sockets java uses Socket class. This class has following two
constructors:
public Socket()
Creates an unconnected socket. Use the connect() method to connect this
socket to a server.
Methods Description
This method connects the socket to the specified host. This method is needed
only when you instantiated the Socket using the no-argument constructor.
importjava.io.*;
importjava.net.*;
classTCPClient {
publicstaticvoidmain(String argv[]) throwsException
{
String sentence;
String modifiedSentence;
BufferedReaderinFromUser =
newBufferedReader(newInputStreamReader(System.in));
Socket clientSocket = newSocket("hostname", 6789);
DataOutputStreamoutToServer =
newDataOutputStream(clientSocket.getOutputStream());
BufferedReaderinFromServer =
newBufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: "+ modifiedSentence);
clientSocket.close();
}}
importjava.io.*;
importjava.net.*;
classTCPServer {
publicstaticvoidmain(String argv[]) throwsException
{
String clientSentence;
String capitalizedSentence;
ServerSocketwelcomeSocket = newServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReaderinFromClient =
newBufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
newDataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}}}
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the
text. Then server will write to the client and client will receive and print the text. The step
goes on.
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}
6. UDP Socket
Some applications that you write to communicate over the network will not require the reliable,
point-to-point channel provided by TCP. Rather, your applications might benefit from a mode of
communication that delivers independent packages of information.
The DatagramPacket and DatagramSocket classes in thejava.net package implement system-
independent datagram communication using UDP.
UDP is contained in two classes:-
java.net.DatagramSocket
java.net.DatagramPacket
6.2. Datagram packet: - A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.
Datagram packets are used to implement a connectionless packet delivery service supported by
the UDP protocol. Each message is transferred from source machine to destination based on
information contained within that packet. That means, each packet needs to have destination
address and each packet might be routed differently, and might arrive in any order. Packet
delivery is not guaranteed.
The format of datagram packet is:
UdpClient.java
import java.net.*;
class UdpClient {
public static void main(String arg[]) {
String str;
DatagramSocket Sock;
DatagramPacket Dp;
Try {
Sock = new DatagramSocket(2000);
byte Buff[] = new byte[1024];
System.out.println("Client ready...");
while(true) {
Dp = new DatagramPacket(Buff,1024);
Sock.receive(Dp);
str = new String(Dp.getData(),0,Dp.getLength());
System.out.println(str);
if(str.equals("exit")) break;
}
Sock.close();
}
catch(Exception e) {
System.out.println("Connection failure..."); }
Finally {
System.out.println("Server Disconnected...");
}}}
OUTPUT:
Udp Server :
E:\>java UdpServer
Enter the data..... Enter 'exit' to stop
hello
exit
Udp Client:
E:\ >java UdpClient
Client ready...
hello
exit
Server Disconnected...
Stream socket
• A dedicated point‐to‐point channel between a clientand server.
• Use TCP (Transmission Control Protocol) for datatransmission.
• Lossless and reliable.
• Sent and received in the same order.
Datagram socket
No dedicated point‐to‐point channel between a client and server.
• Use UDP (User Datagram Protocol) for datatransmission.
• May lose data and not 100% reliable.
• Data may not received in the same order as sent.
7. What is URL?
URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide
Web.
For example:- http://www.javatpoint.com/java-tutorial
A URL contains many information:
Protocol: In this case, http is the protocol.
Server name or IP Address: In this case, www.javatpoint.com is the server name.
Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
File Name or directory name: In this case, index.jsp is the file name.
7.1.URL class: - The java.net.URL class provides many methods. The important
methods of URL class are:-
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public URLConnection openConnection() it returns the instance of URLConnection
i.e. associated with this URL.
Example:-
//URLDemo.java
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}}
Test it Now
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
7.2.URLConnection class
The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.
The openConnection() method of URL class returns the object of URLConnection class.
Syntax: public URLConnection openConnection()throws IOException{}
The URLConnection class provides many methods, we can display all the data of a webpage
by using the getInputStream() method. The getInputStream() method returns all the data of the
specified URL in the stream that can be read and displayed.
Example:-
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}}
catch(Exception e){System.out.println(e);}
} }
Example:-
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}
catch(Exception e){System.out.println(e);}
} }
Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked
8. What Is a Network Interface?
A network interface is the point of interconnection between a computer and a private or public
network. A network interface is generally a network interface card (NIC), but does not have to
have a physical form. Instead, the network interface can be implemented in software. For
example, the loopback interface (127.0.0.1 for IPv4 and ::1 for IPv6) is not a physical device
but a piece of software simulating a network interface. The loopback interface is commonly used
in test environments.
NetworkInterface is useful for a multi-homed system, which is a system with multiple NICs.
Using NetworkInterface, you can specify which NIC to use for a particular network activity.
For example, assume you have a machine with two configured NICs, and you want to send data
to a server. You create a socket like this:
To send the data, the system determines which interface is used. However, if you have a
preference or otherwise need to specify which NIC to use, you can query the system for the
appropriate interfaces and find an address on the interface you want to use. When you create the
socket and bind it to that address, the system uses the associated interface. For example:
NetworkInterfacenif = NetworkInterface.getByName("bge0");
Enumeration<InetAddress>nifAddresses = nif.getInetAddresses();
You can also use NetworkInterface to identify the local interface on which a multicast group is
to be joined. For example:
NetworkInterfacenif = NetworkInterface.getByName("bge0");
MulticastSocketms = new MulticastSocket();
ms.joinGroup(new InetSocketAddress(hostname, port), nif);
NetworkInterface can be used with Java APIs in many other ways beyond the two uses described
here.
Retrieving Network Interfaces
The NetworkInterface class has no public constructor. Therefore, you cannot just create a new
instance of this class with the new operator. Instead, the following static methods are available so
that you can retrieve the interface details from the system: getByInetAddress(), getByName(),
and getNetworkInterfaces(). The first two methods are used when you already know the IP
address or the name of the particular interface. The third method, getNetworkInterfaces()
returns the complete list of interfaces on the machine.
Network interfaces can be hierarchically organized. The NetworkInterface class includes two
methods, getParent() and getSubInterfaces(), that are pertinent to a network interface
hierarchy. The getParent() method returns the parent NetworkInterface of an interface. If a
network interface is a subinterface, getParent() returns a non-null value. The
getSubInterfaces() method returns all the subinterfaces of a network interface.
The following example program lists the name of all the network interfaces and subinterfaces (if
any exist) on a machine.
import java.io.*;
import java.net.*;
importjava.util.*;
import static java.lang.System.out;
One of the most useful pieces of information you can get from a network interface is the list of
IP addresses that are assigned to it. You can obtain this information from a NetworkInterface
instance by using one of two methods. The first method, getInetAddresses(), returns an
Enumeration of InetAddress. The other method, getInterfaceAddresses(), returns a list of
java.net.InterfaceAddress instances. This method is used when you need more information
about an interface address beyond its IP address. For example, you might need additional
information about the subnet mask and broadcast address when the address is an IPv4 address,
and a network prefix length in the case of an IPv6 address.
The following example program lists all the network interfaces and their addresses on a machine:
import java.io.*;
import java.net.*;
importjava.util.*;
import static java.lang.System.out;
You can discover if a network interface is “up” (that is, running) with the isUP() method. The
following methods indicate the network interface type:
The following example expands on the example in Listing Network Interface Addresses by
adding the additional network parameters described on this page:
import java.io.*;
import java.net.*;
importjava.util.*;
import static java.lang.System.out;