Introduction to Network Programming



Networking Basics

Communication between computers connected on a network is fundamentally based on the OSI protocol stack. The various layers in the protocol stack advocate a certain functionality to the network. The various layers and the protocols that are used in each is detailed below.


Java offers a host of classes, which devices can make use of for creating network applications. The java programs are actually implemented in the application layer. The actual network implementation is implements as classes in the package. However, to decide which Java classes your programs should use, we need to understand how TCP & UDP differs.



When two applications want to communicate to each other reliably, they establish a connection & send data back & forth over that connection. This is analogous to making a telephone call. Like the phone company, the TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent.


TCP provides point-to-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all the examples of applications that require a reliable communication channel. The order in which the data is send & received over the network is critical to the success of these applications. When HTTP is used to read from a URL, the data must be received in the order in which it was sent. Otherwise, we end up with jumbled HTML file, a corrupt zip file, or some other invalid information.



The UDP protocol provides a connection-less form of communication between the source and the destination. There is no guarantee that the packet is delivers at the receiver side. It sends independent packets of data, called Datagrams, from one application to another. This is similar to a postal service.

There are many applications which don’t require reliability for the data transfer. In fact the reliable connection may introduce a number of overhead to them. An example is the ping command. The purpose of the ping command is to test the communication between two programs in the network. In fact, ping needs to know about the dropped or out-of-order packets to determine how good or bad the connection is. A reliable channel would invalidate this service altogether.


Client Server Networking


The relationship between two computer programs in which one program, the client, makes a service request to another program, the server, which fulfills this request is what makes the client-server system. A network architecture is the one in which computer processes on the network is either a client or a server; the powerful computers ore processors detected to managing disk drives (file servers), printers (print servers), or network traffic (network servers) are the servers, whereas PCs or workstation on which users run applications are the clients.

Although, the programs within a single computer can use the client/server idea, it is more powerful idea on the network. In a network, the client/server model provides a convenient way to interconnect programs that are distributed efficiently across the different locations. Computer transactions using these are very common. For example, to check your bank account for your computer, a client program in your computer forwards a request to a server program at the bank. That program may in turn forward this request to its own client program that sends a request to a database server at another bank computer to retrieve your data. The balance is then returned back to the bank data client, which in turn serves it back to the client in your PC, which displays the information for you.


Examples of client & server program are:

  • The World Wide Web use web servers that provide service. The clients in WWW are web browsers, such as Google Chrome. The protocol used to communicate between the web servers & browsers is called HTTP. Email is made possible by the SMTP. In this case, the servers such as Microsoft Exchange act as the servers and e-mail programs such as MS outlook acts as the clients.
  • The internet system that converts address such as to numeric IP address such as is managed by a protocol DNS or Domain Name Service. Here your own computer acts as the DNS clients, requesting address look-ups from DNS servers.


Sockets Overview


  • Socket-Definition:

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.


  • TCP/IP and UDP/IP communications:

These are two communication protocols that one can use for socket programming, datagram communication and stream communication.


  • Datagram communication:

The datagram communication protocol, known as UDP (user datagram protocol), is a connectionless protocol, meaning that each time you send datagrams, you also need to send the local socket descriptor and the receiving socket’s address. As you can tell, additional data must be sent each time a communication is made.


  • Stream communication:

The stream communication protocol is known as TCP (transfer control protocol). Unlike UDP, TCP is a connection-oriented protocol. In order to do communication over the TCP protocol, a connection must first be established between the pair of sockets. While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions.
The selection of protocol [UDP or TCP] depends on the client/server application we are writing. The following discussion shows the differences between the UDP and TCP protocols; this might help us to decide which protocol to use.
In UDP, as we have read above, every time we send a datagram, we have to send the local descriptor and the socket address of the receiving socket along with it. Since TCP is a connection-oriented protocol, on the other hand, a connection must be established before communications between the pair of sockets start. So there is a connection setup time in TCP.


In UDP, there is a size limit of 64 kilobytes on datagrams you can send to a specified location, while in TCP there is no limit. Once a connection is established, the pair of sockets behaves like streams: All available data are read immediately in the same order in which they are received.


UDP is an unreliable protocol and so there is no guarantee that the datagrams you have sent will be received in the same order by the receiving socket. On the other hand, TCP is a reliable protocol; it is guaranteed that the packets you send will be received in the order in which they were sent.


In short, TCP is useful for implementing network services such as remote login (rlogin, telnet) and file transfer (FTP) which require data of indefinite length to be transferred. UDP is less complex and incurs fewer overheads. It is often used in implementing client/server applications in distributed systems built over local area networks.


Sockets using UDP connection:

  • Creating a datagram socket.

For programming a client, we can open a socket like this:

//Creating a socketDatagramSocket socket=new DatagramSocket();//create a buffer of size 256

byte[] sendbuf = new byte[256];

byte[] receivebuf = new byte[256];


//create an inet address of the server machine

InetAddress address = InetAddress.getByName(“″);


//create the message

String message=”Hello Datagram server”;



//construct the packet

DatagramPacket packet = new DatagramPacket(sendbuf, sendbuf.length, address, 7632);


//send the packet



// get response

packet = new DatagramPacket(receivebuf, receivebuf.length);





For programming a server, we can open a socket like this:

//Create a socketDatagramSocket socket= new DatagramSocket(7632);byte[] sendbuf = new byte[256];byte[] receivebuf = new byte[256];


// receive request

DatagramPacket packet = new DatagramPacket(receivebuf, receivebuf.length);


String received = new String(packet.getData());



// get the address of the client machine

InetAddress address = packet.getAddress();


// get the port of the client machine

int port = packet.getPort();

dString = “Hello User from “+address;

sendbuf = dString.getBytes();


// construct the packet

packet = new DatagramPacket(sendbuf, sendbuf.length, address, port);


//send the message





Sockets using TCP connection:

  • Opening a socket.

For programming a client, we can open a socket as:

Socket MyClient;try {MyClient = new Socket(“Machine name”, PortNumber);}catch (IOException e)



Where Machine name is the machine you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for standard protocols, such as SMTP, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1023.

For programming a server, we can open a socket like this:

ServerSocketMyService;try {MyServerice = new ServerSocket(PortNumber);}
catch (IOException e) {



When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.



Socket clientSocket = null;try {serviceSocket = MyService.accept();}catch (IOException e)






  • Creating an input stream.

On the client side, you can use the BufferedReader class to create an input stream to receive response from the server:

BufferedReader in = new BufferedReader(newInputStreamReader(socket.getInputStream()));On the server side, you can use DataInputStream to receive input from the client:
BufferedReader in = new BufferedReader(newInputStreamReader(socket.getInputStream()));


  • Creating an output stream.

On the client side, you can create an output stream to send information to the server socket using the class PrintWriter.

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);On the server side, you can use the class PrintStream to send information to the client.PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


  • Closing sockets.

You should always close the output and input stream before you close the socket.

On the client side:try{
catch (IOException e){System.out.println(e);
On the server side:try{
catch (IOException e){






A URL is actually a type of URI, Uniform Resource Identifier. A URI identifies a resource, but doesn’t contain information about how to access the resource. A URL identifies a resource & a protocol for accessing the resource. A URI is represented in Java using the class.


A URL can be broken down into parts, as follows:



The path is also referred to as the filename, and the host is also called the authority. Examples of protocols include HTTP, HTTPS, FTP, and file. For example, the following is a URL to Web page whose protocol is HTTP :


Notice that this URL doesn’t specify a port, in which case the default port for the protocol is used. With HTTP, its 80. The class represents a URL. The URL class has several constructors for creating URLs, which includes :

  1. public URL(String protocol, String host, int port, String file) throws MalformedURLException

Creates a URL by putting together the given parts.

  1. public URL(String protocol,Stringhost,String file) throws MalfromedURLException

Identical to the previous constructor, except that the default port for the given protocol is used

  1. public URL(String url)throws MalfromedURLException

Creates a URL from the given String.

  1. public URL(URL context,String URL) throws MalfromedURLException

Creates a URL by parsing together the  URL& String arguments.


Domain Name Server (DNS)


The internet wouldn’t be a friendly place to navigate if everyone had to remember the ip addresses of web sites. So a parallel hierarchy of names to go with these addresses exists. These are called the Domain name server (DNS).


The Host Names are created using a naming standard called DNS. If DNS wouldn’t have existed we would be ordering books from instead of and we would have to search the web at instead of


The internet has an entire network of DNS server computers throughout the world that looks up host names & provides the corresponding IP address. DNS is related to URL, which stands for Universal resource Locator. URL is a naming convention that can uniquely identify any resources (files) on the internet.


RMI(Remote Method Invocation)


The basic structure of an RMI-based method call involves a client, a server and a registry. To make a call to a remote object, the client first looks up the object it wishes to invoke a method on in the registry. The registry returns a reference to the object (assuming it exists) on the server, which the client can use to invoke any methods that the remote object implements. The client communicates with the remote object via a user-defined interface that is actually implemented by the remote object. The client actually does not deal directly with the remote object at all, but with a code stub that deals with the process of communication between client and server (using, in the default case, sockets).


At the server end, in the pre-Java 2 JDKs(before JDK 1.2), a code skeleton dealt with client communication. In Java 2, the skeleton is no longer needed. Fortunately, the code stub (and skeleton, if necessary) are generated automatically by the RMI Compiler rmic. Remote objects can be invoked with parameters, naturally – these parameters can be entire objects, complete with methods that are passed using serialization. The basic structure is shown in figure:



Fig: Architecture of RMI

The RMI server must implement the remote object’s interface, and hence it must implement the methods in that interface(It can in fact implement other methods as well, but such additional methods will only be available to other objects on the server call – only those methods declared in the interface will be accessible remotely). In addition to the methods of the interface, the server must also undertake a certain amount of initialization – make the remote object(s) available by binding them to the registry.


The client should set up security manager (because the code stub(s) will be downloaded from the server and will be checked), and must lookup the name of the remote object in the registry. The lookup process will return a reference to the remote object (strictly, to the code stub, but from the client’s point of view it looks like the remote object). The remote object can then be treated exactly as if it was local – i.e. you can invoke methods on it in the same way.

Leave a Reply

Your email address will not be published. Required fields are marked *