You are on page 1of 40




One of the biggest secrets about Java is that it makes writing network programs easy. In fact, it is far easier to write network programs in Java than in almost any other language. Major applications have some level of networking built in. IDEs like Eclipse and NetBeans communicate with CVS and SVN repositories.


Antivirus programs like Norton Antivirus check for new virus definitions by connecting to the vendor's web site every time the computer is started.

It is easy for Java applications to send and receive data across the Internet. Easy in terms of the process that we have to follow to transmit data over a network.


Networking adds a lot of power to simple programs. With network programming, a single program can retrieve information stored in millions of computers and of course located anywhere in the world. A single program can communicate with millions of people.

Network applications are having several forms. The most common is between clients and servers. In the simplest case, clients retrieve data from a server and display it. More complex clients filter and reorganize data,

repeatedly retrieve changing data, send data to other people and computers, and can interact with peers in real time for chat, multiplayer games.

Simple servers merely look up some file and return it to the client, but more complex servers often do a lot of processing on the data before answering an involved question. Let's look more closely at the possibilities that open up when you add networking to your programs.


A network is a collection of computers and other devices that can send data to and receive data from each other, more or less in real time. A network is often connected by wires or wireless. Each machine on a network is called a node and nodes that are fully functional computers are also called hosts.

Every node in network has an address, that uniquely identify it.


TCP/IP It is reliable protocol. Data sent using this protocol will be guaranteed to be delivered. Also order of the packet will remain same. UDP It is unreliable protocol. Data sent using this protocol will not guaranteed to be delivered. Also order of the packet may be same or it may change. This protocol is faster then TCP/IP.


As a Java programmer we should not worry about internals of IP address but we should know about how to address IP. On IPV4 host is defined by four-byte number something like So when we sent data over a network header of the packet will include destination address and source address in form of IP address.


If you want to do more than one thing at a time over a network then ports will be required.

Every computer with IP address has several thousand logical ports infact 65,535 to be precise.
They do not exists physically remember they are just abstraction.

Each port can be identified with number ranges from 1 to 65535.

REMEMBER : Port numbers between 1 and 1,023 are reserved for some predefined services. Some well known ports and service running under it.


21 80 25 110 1099 FTP HTTP SMTP POP3 RMI REGISTRY You can send FTP command via this service. Protocol used by World Wide Web. Protocol used for sending email between systems. Transfer emails from host to clients. Registry service for Java remote objects.


It is worlds one of the largest IP based network. Each computer on this network is identified with unique IP address. Another popular network is Intranet, this kind of network is not connected to Internet but they put data in some internal web server.


Many network program will deal with simple input and output means transferring bytes from one system to another system.
In Java I/O works with streams. Input streams are used to read data and output streams are used to write data


Now we know each computer or host on network is identified by unique IP address. But if we see IP address it is always hard to remember right ? For solution of above problem internet designers come up with Domain Name System (DNS). Any DNS will be associated with HOSTNAME that we can remember Like ( and IP address that computer can remember.

Class is Java's high-level representation of an IP address for both IPv4 and IPv6. We will use this class with Socket, ServerSocket, DatagramSocket, MulticastSocket classes.
We can use both a hostname and an IP address in this class. Using InetAddress Objects via three methods.

public static InetAddress getByName(String hostName) throws UnknownHostException public static InetAddress[] getAllByName(String hostName) throws UnknownHostException
public static InetAddress getLocalHost() throws UnknownHostException


On internet data will be transferred in packets of finite size called datagrams. Each datagram contains a header and a payload. The header contains the address and port to which the packet is going, the address and port from which the packet came, and various other information used to ensure reliable transmission. And payload contains the data itself. It is also possible that one or more packets may be lost or corrupted in transmission and need to be retransmitted.

Keeping track of this - splitting the data into packets, generating headers, parsing the headers of incoming packets, keeping track of what packets have and haven't been received, and so on - is a lot of work and requires a lot of intricate code.

We do not have to worry about above things. Sockets shield the programmer error detection, packet sizes, packet retransmission, network addresses and more



A socket is a connection between two hosts. It can perform few operations.

Connect to a remote machine Send data Receive data Close a connection Bind to a port Listen for incoming data Accept connections from remote machines on the bound port

Java program will require to use Client Socket via following way.
Create a new Socket using constructor. Socket will try to connect to remote host.

Once the connection is established, the local and remote hosts get input and output streams from the socket and use those streams to send data to each other. This connection is full-duplex. Both hosts can send and receive data simultaneously.

The class is Java's fundamental class for performing client-side TCP operations. To create Client socket call constructor of Socket class. public Socket(String host, int port) throws UnknownHostException, IOException This constructor creates a TCP socket to the specified port with specified host and attempts to connect to the host.`


For servers to accept connections, Java provides a class that represents server sockets. Actually server socket's job is to wait for incoming connection. ServerSocket will listen for incoming TCP connections. When a client on any host attempts to connect to that port, the server will negotiates with the connection and returns a regular Socket object representing the socket between the two hosts.

Once a ServerSocket has set up the connection, the server uses a regular Socket object to send data to the client. You can create a server socket via following constructors, there are four public ServerSocket constructors

public ServerSocket(int port) throws BindException, IOException

This constructor creates a server socket on the port specified in the argument. If you pass 0 for the port number, the system selects an available port for you.

public ServerSocket(int port, int queueLength) throws BindException, IOException This constructor opens a server socket on the specified port with a queue length of your choosing.queue length is how many requires you want to keep in queue after that server will refuse the connection.

public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException The only difference in this constructor is to listen on specific address. public ServerSocket( ) throws IOException Create a ServerSocket object but does not actually bind it to any port, So it cannot initially accept any connections. Later on you have to call bind() methods.




TCP is designed for reliable transmission of data. If by any case data is lost or damaged during transmission, TCP will resent data. Also if packets of data arrive out of order, TCP puts them back in the correct order; if the data is coming too fast for the connection, TCP adjust the speed so packets won't be lost.

Moral of the story is a program never needs to worry about receiving data that is out of order or incorrect if it uses TCP.
However, this reliability comes at a price. That price is speed. Establishing and tearing down TCP connections can

take a fair amount of time, particularly for protocols such as HTTP, which tend to require many short transmissions.

The User Datagram Protocol (UDP) is an alternative protocol for sending data over IP that is very quick. Unfortunately it is not reliable. When you send UDP data, you have no way of knowing whether it arrived, also data arrived in the order in which you sent them.
However, the pieces that do arrive generally arrive quickly.

Java's implements UDP into two classes: DatagramPacket and DatagramSocket. The DatagramPacket class package bytes of data into UDP packets called datagrams and lets you unpackage datagrams that you receive.

A DatagramSocket sends as well as receives UDP datagrams.

To send data, you put the data in a DatagramPacket and send the packet using a DatagramSocket. To receive data, you receive a DatagramPacket object from a DatagramSocket and then read the contents of the packet. In UDP, the address to which it is directed, is included in the packet itself. the socket only needs to know the local port on which to listen or send.


DatagramPacket uses different constructors depending on whether the packet will be used to send data or to receive data.

Constructors for sending datagrams

public DatagramPacket(byte[] buffer, int length)

public DatagramPacket(byte[] buffer, int offset, int length)

DatagramPacket uses different constructors depending on whether the packet will be used to send data or to receive data.
Constructors for sending datagrams

public DatagramPacket(byte[] buffer, int length)

public DatagramPacket(byte[] buffer, int offset, int length)

When a socket receives a datagram, it stores the datagram's data part in buffer beginning at buffer[0] and continuing until the packet is completely stored or until length bytes have been written into the buffer. If the second constructor is used, storage begins at buffer[offset] instead. Otherwise, these two constructors are identical.


public DatagramPacket(byte[] data, int length,InetAddress destination, int port) public DatagramPacket(byte[] data,int offset,int length,InetAddress destination, int port)

public DatagramPacket(byte[] data, int length, SocketAddress destination, int port) public DatagramPacket(byte[] data, int offset, int length,SocketAddress destination, int port)

Each constructor creates a new DatagramPacket to be sent to another host. The packet is filled with length bytes of the data array starting at offset or 0 if offset is not used.


To send or receive a DatagramPacket, you must open a datagram socket. In Java, a datagram socket is created and accessed through the DatagramSocket class.

Following are the constructors.

public DatagramSocket( ) throws SocketException

This constructor creates a socket that is bound to an anonymous port

public DatagramSocket(int port) throws SocketException This constructor creates a socket that listens for incoming datagrams on a particular port.


The sockets that we have seen so far are unicast: they provide point-to-point communication. Unicast sockets create a connection with two well-defined endpoints. there is one sender and one receiver and, although they may switch roles, at any given time it is easy to tell which is which.

However, although point-to-point communications serve many, if not most needs, many tasks require a different model. For example, a television station broadcasts data from one location to every point within range of its transmitter.

The signal reaches every television set, whether or not it's turned on and whether or not it's tuned to that particular station.

Multicasting is broader than unicast, point-to-point communication but narrower and more targeted than broadcast communication. Multicasting sends data from one host to many different hosts, but not to everyone. the data only goes to clients that have expressed an interest by joining a particular multicast group.

IP also supports broadcasting, but the use of broadcasts is strictly limited. Protocols require broadcasts only when there is no alternative. You multicast data using the class, a subclass of MulticastSocket's behavior is very similar to DatagramSocket's: you put your data in DatagramPacket objects that you send and receive with the MulticastSocket.

To receive data that is being multicast from a remote site, first create a MulticastSocket with the MulticastSocket( ) constructor. Next, join a multicast group using the MulticastSocket's joinGroup( ) method. Once you've joined the multicast group, you receive UDP data just as you would with a DatagramSocket.