You are on page 1of 11

Java Socket Programming Basics

Objectives:
Appreciate low-level network communication using sockets Demonstrate client-server architecture through socket programming Fully understand the difference between datagram communication and stream communication Learn the Java classes that facilitate socket communication

Concepts
In order for us to write meaningful network-based application, we need to have a firm grasp of the factors involved in implementing these applications and the sound knowledge of the fundamental network programming models.

CLIENT-SERVER ARCHITECTURE
request

respond SERVER Network CLIENT

Basically, network-based application systems consist of a server, a client and a media for communication. The server machine hosts an application that offers requested services from clients. The client machine runs a program that makes request for services. The setup shown above uses the networking services provided by the transport layer of the TCP/IP protocol stack. The most widely used programming interfaces for these protocols are sockets. There are two protocols used for communication datagram and stream communication protocol. The datagram protocol as known as User Datagram Protocol (UDP) is a connectionless protocol. It sends independent packets of data, called datagrams. The protocol does not guarantee you the arrival and sequencing of the packets sent. During the communication, you need to send the local socket descriptor and the receiving sockets address. The stream communication is also known as the Transmission Control Protocol. It is a connection-oriented protocol. A connection must be established between two sockets prior to communication. While the server socket listens for connection request, the other (client socket) asks for

a connection. Once the sockets have been connected, they can be used to transmit data in both directions.

Socket and Socket Based Communication


Sockets provide an interface for programming networks at the transport layer. Handling sockets is treated like file handle that is why socket programming is very much similar to performing file I/O. Socket-based communication is independent of a programming language used for implementing it. A server program runs on a specific computer and has a socket that is bound to a specific port. The server listens to the socket for a client to make a connection request. If everything goes well, the server accept the connection . Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket (a different port) so that it can continue to listen to the original socket for connection request s while serving the connected client.

Java Programming and the Java.net class


A socket is one end-point of a two-way communication link between two programs running on the network. Socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. 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 simplifying the complexity involved in creating client and server programs are:

Classes :
o o o o o ContentHandler DatagramPacket DatagramSocket DatagramSocketImpl HttpURLConnection

o o o o o o o o o

InetAddress MulticastSocket ServerSocket Socket SocketImpl URL URLConnection URLEncoder URLStreamHandler

Interfaces
o o o o ContentHandlerFactory FileNameMap SocketImplFactory URLStreamHandlerFactory

Exceptions
o o o o o o o BindException ConnectionException MalformedURLException NoRouteToHostException ProtocolException SocketException UnknownHostException

TCP/IP Socket Programming


The two key classes from the java.net package used in creation of server and client programs are: o ServerSocket o Socket A server program creates a specific type of socket that is used to listen for client requests. o In the case of a connection requests, the program creates a new socket through which it will exchange data with the client using input and output streams.

Algorithm for A Simple Server Program in Java


1. Open the Server Socket: ServerSocket server = new ServerSocket(PORT);

2. Wait for the client request. Socket client = server.accept();

3. Create I/O streams for communicating to the client


DataInputStream is = new DataInputStream( client.getInputStream()); DataOutputStream os = new DataOutputStream( client.getOutputStream());

4. Perform communication with client //Receive from client String line = is.readLine( ); //Send to client os.writeBytes( hello\n);

5. Close socket. client.close( );

Algorithm For A Simple Client Program in Java


1. Create a Socket Object Socket client = new Socket ( SERVER, PORT );

2. Create I/O streams for communicating with the server. DataInputStream is = new DataInputStream(client.getInputStream( )); DataOutputStream os = new DataOutputStream(client.getOutputStream( ));

3. Perform I/O or communication with the server. //Receive data from the server String line = is.readLine( ); //Send data to the server os.writeBytes(Hello\n);

4. Close the socket when done. client.close();

Example Program 1.1 SimpleServerSocketCreate.java


import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class SimpleServerSocketCreate { public static void main(String args[]) { ServerSocket server = null; int port = 4000; try { System.out.println("Attempting To Bind To TCP port " + port + "...."); server = new ServerSocket(port); } catch(IOException ioe) { System.err.println("Error binding to port: " + port); ioe.printStackTrace(); System.exit(1); } boolean b = true; while(b){ System.out.println("Listening For Connections..."); try { Socket socket = server.accept(); System.out.println("A communication request has been granted"); //This is the part where a thread is spawned to perform communications socket.close(); } catch(IOException ioe){ ioe.printStackTrace(); } } //end while } //end main }//end classass

Example Program 1.2. SimpleSocketCreate.java


import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class SimpleSocketCreate { public static void main(String[] args) { String SERVER = "localhost"; int PORT = 4000;

try{ System.out.println("Attempting To Connect To A TCP service on " + SERVER + ":" + PORT); Socket client = new Socket(SERVER, PORT); System.out.println("Connection Established"); //this is the part where we perform communication with the server client.close(); } catch(UnknownHostException uhe){ System.err.println("Could not resolve hostname: " + uhe.getMessage()); } catch(IOException ioe){ ioe.printStackTrace(); } } }

Internet Addressing and Naming


The Internet
The Internet Protocol (IP) is the core protocol of the Internet. o Internet Protocol The basic communications model of the Internet Protocol is that of a connectionless, best-effort packet service. Internet nodes wishing to send data across the network to a destination node must first break down that data into smaller data-segments called packets. o Each packet is then transmitted individually on a hop-by-hop basis towards the destination node. Routers perform the forwarding function. o IP packets are forwarded with best efforts so they may not be lost, get corrupted or arrive out of order at the destination. The three basic functions of Internet communications are addressing, naming and routing. o An Internet address uniquely identifies the location of an Internet node. It is important to remember that there is no direct mapping between Internet addresses and physical location. o In order to communicate with an Internet node identified by a name, an application must look up (resolve) the Internet address for that name. o Internet nodes forward packets towards their destination address using local routing information. Interne nodes used to forward packets between destinations are called routers.

Internet Addresses
Internet addresses are used to identify the location of Internet nodes. o All data transmitted over the Internet must be addressed to a single OP address The Internet provides a communications mechanism that moves data segments (packets) from one source node to a destination node using best effort

Shown above is each packet is marked with the IP address of the source node as well as the address of the destination node o The client is identified by the IP address 128.59.22.38 o The server is identified by the IP address 204.148.170.161 o The main focus is the end to end packet delivery function of the Internet o The client host sends an IP packet containing the message Hello and addressed to the Internet node located at address 204.148.170.161 o The role of the Internet is to deliver that packet to the server using best effort. o The only guarantee that the Internet Protocol is that if the packet is delivered to the server, it will have the correct header

Internet Naming (Domain Name System)


Domain Name System is a naming mechanism that provides location-dependent and humanfriendly identities to Internet nodes. DNS creates an extensible distributed hierarchical naming system. DNS defined both a hierarchical data model for Internet name assignment as well as a protocol for querying the distributed data structure.

DNS Namespace
The DNS namespace forms a hierarchical tree structure. o Each node in the tree has a label of length up to 63 bytes o All nodes except the root node must have a non-empty text label and all children of a node must have unique labels

A domain name uniquely identifies a node in the tree o Domain names are created by traversing from any node in the tree up to the root and appending a period . between each label

null(root)

edu columbia cs aqua


DNS Record Types

com wrox www forexworld

math

Resource Records contain information about the particular node such as its Internet address. DNS permits attributes (resource records) in both nodes with children and leaf nodes Every resource record must have an owner, class, TTL and type attribute o The owner is the domain name to which the resource record belongs o The class refers to the protocol family/version of the record The IPv4 records are of type IN o The TTL stands for Time-To-Live and indicates how long (in seconds) the record can be cached before it is discarded o The type attribute characterizes the information stored in the resource record Owner Class TTL Type Value www.forexworld.com.au IN 60480 A 204.148.170.161

The core DNS specification specifies the following resource record types Type A CNAME Description A host address such as 204.148.170.161 Marks the domain name as an alias for another domain. When a domain name contains a CNAME resource record, it cannot contain other record types. As a result, alias domains cannot add additional information (resource records). For example, the domain www.forexworld.com.au. may be used as an alias for the real server host server.forexworld.co.au. Identifies the CPU and OS used by a host as a string Identifies the domain name handling the e-mail (SMTP) service for this domain and provides the priority with which it should be used Points to another part of the domain space (usually used for supporting reverse

HINFO MX PTR

NS

lookups) The authoritative name server for the domain.

DNS Distributed Architecture


Name servers are programs that hold information about a domain and its children Resolvers are client programs that query name servers in order to locate a particular domain name and obtain its resource record information. o Resolvers are configured with the IP address of one or more local name servers o Name servers and resolvers communicate using the DNS protocol via the well-known UDP port 53 or TCP port 53

java.net.InetAddress
Java encapsulates the concept of an IP address in a class the class is part of the java.net package and is called InetAddress. Can perform basic domain name to address and address to domain name queries. InetAddress is not capable of retrieving other resource record such as MX, HINFO and so on InetAddress class is also missing useful operations for creating addresses out of byte-arrays, obtaining all IP addresses of the local host and the use of addresses as network masks.

java.net.InetAddress
+getByName(): java.net.InetAddress +getAllByName(): java.net.InetAddress[ ] +getLocalHost(): java.net.InetAddress +getHostName(): String +getAddress(): byte[ ] +getHostAddress(): String +isMulticastAddress(): boolean

Example 1.3: DNS Lookup Example


import java.net.InetAddress; public class DNSResolver { public static void main(String[] args){ if(args.length != 1) { System.err.println("Usage: DNSResolver [ <name> | <address"); System.exit(1); } //Determine if argument is an IP address of a domain name //Since domain name cannot start with a number, check for that.

boolean try {

isReverseLookup = Character.isDigit(args[0].charAt(0));

InetAddress[] addresses = InetAddress.getAllByName(args[0]); for(int a = 0; a < addresses.length; a++) { InetAddress address = addresses[a]; if(isReverseLookup) { if(address.getHostAddress().equals(address.getHostName())) { System.out.println("Could not reverse resolve " + address.getHostAddress()); } else { System.out.println(address.getHostAddress() + " reverse resolves to " + address.getHostName()); } } else { System.out.println(address.getHostName() + " resolves to " + address.getHostAddress()); } } } catch(java.net.UnknownHostException e) { System.err.println("Cannot resolve " + args[0]); System.exit(1); } } }

Example 1.4: LocalHost.java


import java.net.InetAddress; /* A command utility that prints the localhost name and address obtained by InetAddress.getLocalHost() and performs a reverse lookup on the address to obtain the name */ public class LocalHost { public static void main(String[] args) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println("Local address: " + address.getHostAddress()); System.out.println("Local hostname: " + address.getHostName()); } catch (java.net.UnknownHostException uhe) { System.err.println("Cannot determine local host name and address: " + uhe.getMessage());

System.exit(1); } } }

You might also like