Java - Network programming

Table of Contents

The term network programming refers to writing programs that run across multiple devices ( computers), in which all devices are connected via a network to one another.

Network Layers

The most important layers of TCP/IP Networking is as follows:

Application Layer (http,ftp,telnet,smtp,dns,…)
Transport Layer (TCP,UDP,…)
Network Layer (IP,…)
Physical + Data Link Layer (Arpanet,SatNet,Lan, …)


  • TCP : Transmission Control Protocol : Is a connection- based protocol that provides a reliable flow of data between two computers. Used when two applications want to communicate reliably

    • It is Connection Based
    • Data is get in the same order it was sent (via Streams)
    • Transmission guarantied, or error is reported.
    • Example: HTTP, FTP, SMTP, TELNET,
  • UDP : User Datagram Protocol : Is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival.

    • Not connection based
    • Communication is not guaranteed
    • Datagram : A packet sent by UDP protocol.
    • The order of datagrams are not guaranteed.
    • Example: Radio, Clock Server, Ping,

IP (Internet Protocol) - Network layer protocol

An IP address (internet protocol address) is a numerical representation that uniquely identifies a specific interface on the network.

  • IP Address : A unique 32 bit number.
  • Dotted Decimal Notation :
    • Range : –
    • Every host and router in the Internet has an IP address, which encodes its network number and host number.
  • Classes of IP Addresses
    • Class A : 0{7 bits Network}.{24 bits Host}
    • Class B : 10{14 bits Network}.{16 bits Host}
    • Class C : 110{21 bits Network}.{8 bits Host}
    • Class D : 1110{Multicast address}
    • Class E : 11110{Reserved for future use}
  • Special IP-addresses
    • : This host
    • : Broadcast on local network
    • 127.?.?.? : Loopback


Generally a computer has a single physical connection (e.g. via IP address) to the network. However the data can be intended to different applications, a port is a communication endpoint that can be used by one application. A port number is a 16-bit unsigned integer, thus ranging from 0 to 65535.

  • A port is a unique place within the machine. (Abstraction)
  • The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer
    • For TCP, port number 0 is reserved and cannot be used
    • For UDP, the source port is optional and a value of zero means no port.

Well Known Ports

NamePort NumberDescription
qotd17/tcpQuote of the Day
qotd17/udpQuote of the Day
ftp21/tcpFile Transfer (control)
ssh22/tcpSecure Shell Login
smtp25/tcpSimple Mail Transfer
http80/tcpWorld Wide Web HTTP
nntp119/tcpusenet, Network News Transfer Protocol
https443/tcpSecure World Wide Web HTTP

URL - Uniform Resource Locater

A URL is a reference (an address) to a resource on the Internet. It has two main components:

  • Protocol Identifier
  • Resource Name

Example :

  • http is the Protocol Identifier
  • // is the Resource Name

The Resource Name may contain

  • HostName: The name of the machine
  • FileName: The pathname of the file on the machine
  • Port Number: The port number to which to connect (Typically Optional)
  • Reference: A reference to a named anchor within a resource (Typically Optional)

There are two classes for URL processing in Java:

  • : Represents a URL resource
  • : An opened connection to a URL resource

Creating an absolute URL object can be done using constructor URL(String)

URL myurl = new URL(“”) ;

Creating a URL relative to another can be done like this:

URL myurl = new URL(“”) ;
URL imprint = new URL(myurl, “/en/content/imprint”) ;

Other URL Constructors are:

  • URL(String protocol, String host, int port, String file)
  • URL(String protocol, String host, String file)
  • URL(String spec)
  • URL(URL context, String spec)

All constructors throw MalformedURLException

A URL can be parsed using the following funtions:

  • String getProtocol()
  • String getHost()
  • int getPort()
  • String getFile()
  • String getRef()


import* ;
public class ParseURL {
    public static void main(String[]args) throws MalformedURLException {
        URL url = new URL("") ;
        System.out.println("Protocol = "+url.getProtocol()) ;
        System.out.println("Host     = "+url.getHost()) ;
        System.out.println("FileName = "+url.getFile()) ;
        System.out.println("Port     = "+url.getPort()) ;
        System.out.println("Reference= "+url.getRef()) ;
/* Output */
Protocol = https
Host     =
FileName = /en/content/imprint
Port     = 443

Reading from URL

Reading directly from a URL using openStream() method that returns an InputStream


import* ;
import* ;
public class URLReader {
    public static void main(String[] args) throws Exception {
        URL url = new URL("") ;
        BufferedReader br = new BufferedReader (new InputStreamReader(url.openStream())) ;
        String line ;
        while ((line=br.readLine())!=null)
            System.out.println(line) ;
        br.close() ;

Connecting to a URL

URL’s openConnection() method is used for connecting to a URL. URLConnection openConnection() throws IOException ;


try {
    URL url = new URL("") ;
    URLConnection uc = url.openConnection() ; 
catch (MalformedURLException e) { … }
catch (IOException e) { … }

Reading from a URL connection:

import* ;
import* ;
public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL url = new URL("") ;
        URLConnection uc = url.openConnection() ;
        BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line ;
        while ((line=br.readLine())!=null)
            System.out.println(line) ;
        br.close() ;

Writing to a URL connection:

import* ;
import* ;
public class Reverse {
    public static void main(String[]args) throws Exception {
    if (args.length<1) {
        System.err.println("Usage: java Reverse <String>") ; System.exit(1) ;
    String stringToReverse = URLEncoder.encode(args[0],"UTF-8") ;
    URL url = new URL("") ;
    URLConnection uc = url.openConnection() ;
    uc.setDoOutput(true) ;
    PrintWriter out = new PrintWriter(uc.getOutputStream()) ;
    out.println("string="+stringToReverse) ;
    out.close() ;
    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())) ;
    String line ;
    while ((line=in.readLine())!=null)
        System.out.println(line) ;


A Socket is the end point of a two-way communication link between two programs running on the network. Socket is a software abstraction to represent the “terminals” of a connection. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. There two stream-based Socket classes:

  • ServerSocket : for server, On connection returns a new Socket
  • Socket : for client, containing getInputStream() and getOutputStream() functions

Socket Example - Echo

import* ;
import* ;
public class EchoClient {
	public static void main(String[]args) throws IOException {
		Socket socket = null ;
		PrintWriter out = null ;
		BufferedReader in = null ;
		String host = "localhost" ;
		try {	
			socket = new Socket(host,7) ;	// Port number 7
			out = new PrintWriter(socket.getOutputStream(),true) ;
			in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
		} catch (UnknownHostException e) {
			System.err.println("Dont know host: "+host) ;
			System.exit(-1) ;
		} catch (IOException e) {
			System.err.println("Cannot get IO for connection to "+host) ;
			System.exit(-1) ;
		BufferedReader stdin = new BufferedReader(new InputStreamReader( ;
		String input ;
		while ((input=stdin.readLine())!=null) {
			out.println(input) ;
			System.out.println("echo: "+in.readLine()) ;
		out.close() ;  in.close() ;  stdin.close() ;  socket.close() ;	// Order important

Socket Connection for Server

The basic program flow for Sever for creating a socket is as follows:

  1. Create a ServerSocket
  2. Call ServerSocket.accept() to get a Socket connection
  3. Open input stream and output stream to that socket
  4. Read from and write to streams according to the Protocol
  5. Close the streams
  6. Close the socket
    • Optional: Return to 2 to get another connection
    • For Server allowing multiple connections, 3-6 must be in another thread

Socket Connection for Client

The basic program flow for Client for connecting to a socket is as follows:

  1. Open Socket
  2. Open an input stream and output stream to the socket
  3. Read from and write to the stream according to the server’s protocol
  4. Close the streams
  5. Close the socket
    • Only step 3 differs from client to client, depending on the server


Serialization is the transformation of an object's state into a byte stream; deserialization does the opposite. Serialization is, stated differently, the conversion of a Java object into a static stream (sequence) of bytes that can then be saved to a database or transferred over a network.

To serialize an object:

OutputStream out = ...;   
MyObject anObject = ...;
ObjectOutputStream oOut = new ObjectOutputStream (out);
oOut.writeObject (anObject); 

To unserialize an object:

InputStream in = ...;   
ObjectInputStream oIn = new ObjectInputStream(in);   
MyObject anObject = (MyObject)(oIn.readObject()); 

Object output streams provide:

writeObject (Object);   
writeInt (int);   
writeBoolean (boolean);   ... 

Object input streams provide:

Object readObject ();   
int readInt ();   
boolean readBoolean ();   ... 

Not all objects can be serialized. Objects which can be serialized are called serializable. Serializable objects are instances of classes:

class MyClass implements Serializable { 

Note that the Serializable interface is empty. Internally the Serializable interface provides version control. Many container classes are already marked as Serializable.

Note that the static fields (as opposed to an object) of a class are not serialized. Note also that we may use the transient keyword to ignore class fields during serialization:

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    static String country = "GERMANY";
    private String firstName;
    private String LastName;
    transient int age;
    // getters and setters

Serial Version UID

The JVM associates each serializable class with a (long) version number. It is used to verify that the objects saved and loaded have the same attributes, and are thus compatible with serialization.

Most IDEs can generate this number automatically, and it is based on the name of the class, its attributes and associated modifiers of access. Any changes will give rise to a different number and may cause an InvalidClassException.

If a serializable class does not declare serialVersionUID, then the JVM will automatically generate one at run time. It is highly recommended, however, that each class declare its serialVersionUID as the generated one is dependent on the compiler and thus may result in unexpected InvalidClassExceptions.


  1. Exercise:
    • Write a TCP client/server system in which the client program sends a string to a server program which returns the reverse of that string.