You are on page 1of 65

Chapter 5: Networking

Introduction

1
Introduction

• Internet and WWW have emerged as global media for


communication everywhere and changed the way we
conduct science, engineering, and e-commerce.

• They are also changing the way we learn, live, enjoy ,


communicate, interact, engage, etc. The modern life
activities are getting completely centered around or
driven by the Internet.

2
Introduction cont’d…

• The Internet is all about connecting machines


together.
• One of the most exciting aspects of Java is that it
incorporates an easy-to-use, cross platform model for
network communications that makes it possible to
learn network programming without years of study.
This opens up a whole new class of applications to
programmers.

3
Some Background
• Network
• Client server computing
• Hosts
• Internet Addresses
• Ports
• Protocols
• URL

4
What is network?
• A network is a collection of devices that share a common
communication protocol and a common communication medium (such
as network cables, dial-up connections, and wireless links).
• 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.

5
Client Server Computing
• At a basic level, network-based systems consist of a server ,
client , and a media for communication as shown in next
slide figure.
• A computer running a program that makes a request for
services is called client machine.
• A computer running a program that offers requested services
for one or more clients is called server machine.
• The media for communication can be wired or wireless
network.

6
Client Server Computing Elements

• Client, Server, and Network

st
e
qu
Client
Re Server
Network
Re
su
l t
Client machine
Server machine

7
What is Internet protocol(ip)

• Every computer on the Internet has one Internet address that


uniquely identifies each computer on the internet. Originally, all
Internet addresses consisted of 32-bit values, organized as four 8-bit
values. This address type was specified by IPv4 (Internet Protocol,
version 4).
• This is typically written in dotted quad format like 128.250.25.158
where each byte is an unsigned value between 0 and 255.
• Hence, IP addresses are mapped to names like www.yahoo.com or
www.google.com, which are easier to remember.
• Internet supports name servers that translate these names to IP
addresses. Domain Naming Service (DNS) maps names to numbers.

8
The InetAddress Class in java

• The java.net.InetAddress class represents an IP address.


• It converts numeric addresses to host names and host
names to numeric addresses.
• It is used by other network classes like Socket and
ServerSocket to identify hosts.
• Creating InetAddresses
• All addresses that are created must be checked with
DNS

9
The InetAddress Class in java cont..

• Some useful methods:


• String getHostName()
• String getHostAddress()
• InetAddress getLocalHost()
• InetAddress[] getAllByName(String hostName)
• boolean equals(Object obj)
• byte[] getAddress() returns the IP address in byte format
(as opposed to dotted decimal notation)
• InetAddress getByName(String hostName)

10
The InetAddress Class in java cont..

Example1:
import java.net.*;
public class LocalHostDemo{
public static void main(String args[]){
System.out.println ("Looking up local host");
try{
// Get the local host
InetAddress localAddress =InetAddress.getLocalHost();
System.out.println ("IP address:" +localAddress.getHostAddress());
}catch (UnknownHostException uhe){
System.out.println ("Error - unable to resolve localhost");}}}

11
The InetAddress Class in java cont..

• Example2:
• import java.net.*;
• public class inet {
• public static void main(String[] args){
• try {
• InetAddress inet1 =InetAddress.getByName("localhost");
• System.out.println("HostAddress=" + inet1.getHostAddress());
• InetAddress inet2 =InetAddress.getByName("127.0.0.1");
• System.out.println("HostName=" + inet2.getHostName());
• if (inet1.equals(inet2))
• System.out.println("Addresses are equal");
• }catch (UnknownHostException uhe) uhe.printStackTrace(); }} }

12
Ports

• In general a host has only one Internet address


• This address is subdivided into 65,536 ports
• Ports are logical abstractions that allow one host to
communicate simultaneously with many other hosts
• Many services run on well-known ports. For example:
- http tends to run on port 80
- FTP tends to run on port 21/20
- TELNET tends to run on port 23
- SMTP tends to run on port 25

13
Protocols
• A protocol defines how two hosts talk to each other. It is rules
that facilitate communications between machines
 Examples:
 HTTP: HyperText Transfer Protocol
 FTP: File Transfer Protocol
 SMTP: Simple Message Transfer Protocol
 TCP: Transmission Control Protocol
 UDP: User Datagram Protocol, good for, e.g., video
delivery)
 Protocols are standardized and documented, So machines can
reliably work with one another

14
URL
• A URL, short for "Uniform Resource
Locator", is a way to unambiguously identify
the location of a resource on the Internet.
Examples of Url
http://java.sun.com/
ftp://ftp.info.apple.com/pub/
mailto:elharo@metalab.unc.edu
telnet://utopia.poly.edu

15
The Pieces of a URL
• the protocol, aka scheme
• the authority
• user info
• user name
• password
• host name or address
• port
• the path, a.k.a. file
• the ref, a.k.a. section or anchor
• the query string

16
The java.net.URL class

• A URL object represents a URL.


• The URL class contains methods to
• create new URLs
• parse the different parts of a URL
• get an input stream from a URL so you can read data
from a server
• get content from the server as a Java object
Content and Protocol Handlers
• Content and protocol handlers separate the data being
downloaded from the protocol used to download it.

17
The java.net.URL class cont..

• The protocol handler negotiates with the server and parses any headers.
It gives the content handler only the actual data of the requested
resource.
• The content handler translates those bytes into a Java object like an
InputStream or ImageProducer.
• When the virtual machine creates a URL object, it looks for a protocol
handler that understands the protocol part of the URL such as "http" or
"mailto".
• If no such handler is found, the constructor throws a
MalformedURLException.

18
The java.net.URL class cont..

• The exact protocols that Java supports vary from implementation to


implementation though http and file are supported pretty much everywhere.
• URL CONSTRUCTOR IN java.net.URL
public URL(String u)
public URL(String protocol, String host, String file)
public URL(String protocol, String host, int port, String file)
public URL(URL context, String url)
public URL(String protocol, String host, int port, String file,
URLStreamHandler handler)
public URL(URL context, String url, URLStreamHandler handler)
Note: All constructor throws MalformedURLExecption

19
Constructing URL Objects
• An absolute URL like http://www.poly.edu/fall97/grad.html#cs
try {
URL u = new URL("http://www.poly.edu/fall97/grad.html#cs");
}
catch (MalformedURLException e) {}

20
Constructing URL Objects cont..

• You can also construct the URL by passing its pieces to the
constructor, like this:
• URL u = null;
• try {
• u = new URL("http","www.poly.edu", 8000,
"/fall97/grad.html#cs");
• }
• catch (MalformedURLException e) {}

21
Constructing URL Objects cont..

• Creates URLs relative to a given URL. For example,


try {
URL u1 = new URL("http://metalab.unc.edu/index.html");
URL u2 = new URL(u1, "books.html");
}
catch (MalformedURLException e) {}
• This is particularly useful when parsing HTML.

22
Parsing URL

• The java.net.URL class has five methods to split a URL into its
component parts. These are:
public String getProtocol()
public String getHost()
public int getPort()
public String getFile()
public String getRef()
public String getAuthority() // support by JDK 1.3
public String getUserInfo()
public String getQuery()

23
Missing Pieces

• If a port is not explicitly specified in the URL it's set to -1. This
means the default port.
• If the ref doesn't exist, it's just null. Better yet, test to see that
it's non-null before using it.
• If the file is left off completely, e.g. http://java.sun.com, then
it's set to "/".

24
Reading data from a URL

• The openStream() method connects to the server specified in the URL


and returns an InputStream object fed by the data from that connection.
• public final InputStream openStream() throws IOException
• Network connections are less reliable and slower than files. Buffer with
a BufferedReader or a BufferedInputStream.

25
Reading data from a URL cont..
• Example:
import java.net.*;
import java.io.*;
public class Webcat {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try { URL u = new URL(args[i]);
InputStream in = u.openStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
String theLine;
while ((theLine = br.readLine()) != null) {
System.out.println(theLine); }}
catch (IOException e) { System.err.println(e);} }}}

26
Datagram
• Before data is sent across the Internet from one host to another using
TCP/IP, it is split into packets of varying but finite size called
datagrams.
• Datagrams range in size from a few dozen bytes to about 60,000 bytes.
• Packets larger than this must be split into smaller pieces before they
can be transmitted.
• If one packet is lost, it can be retransmitted without requiring
redelivery of all other packets.
• If packets arrive out of order they can be reordered at the receiving end
of the connection.

27
Datagram cont..
• Datagrams are mostly hidden from the Java programmer.
• The host's native networking software transparently splits
data into packets on the sending end of a connection, and
then reassembles packets on the receiving end.
• Instead, the Java programmer is presented with a higher
level abstraction called a socket.

28
What is Socket?

• A socket is a reliable connection for the transmission of data


between two hosts. It is an endpoint of a two-way communication
link between two programs running on the network.
• Sockets isolate programmers from the details of packet encodings,
lost and retransmitted packets, and packets that arrive out of order.
• Socket-based communication is independent of a programming
language used for implementing it. That means, a socket program
written in Java language can communicate to a program written
using non-Java (say C or C++) socket program.

29
The java.net package
• The java.net package provides support for the two common network
protocols:
1. TCP communication:
 Socket
 ServerSocket
2. UDP communication:
 DatagramPacket
 DatagramSocket
 MulticastSocket

30
Socket Programming with TCP
• TCP (Transmission Control Protocol)
A connection-oriented protocol.
Allows reliable communication between two applications.
Usually used over the Internet with IP as TCP/IP
Resembles making a telephone call
• The person placing the telephone call – client
• The person waiting for a call – server
 The java.net.ServerSocket and java.net.Socket classes are
the only two classes you will probably ever need to create
a TCP/IP connection between two computers.

31
Socket Programming with TCP cont..

For a secure connection, SSLServerSocket and SSLSocket classes


in the javax.net.ssl package are used.
Guarantees that data sent from one end of the connection actually
gets to the other end and in the same order it was sent. Otherwise,
an error is reported.
The Hypertext Transfer Protocol (HTTP), File Transfer Protocol
(FTP), and Telnet are all examples of applications that require a
reliable communication channel.

32
Socket and ServerSocket class
• A program can read from a socket or write to a socket as simply as
reading from a file or writing to a file.

• A socket is bound to a port number so that the TCP layer can identify
the application that data destined to be sent.

• Java’s .net package provides two classes:


1. Socket – for implementing a client
2. ServerSocket – for implementing a server

33
Socket operations
• There are four fundamental operations a socket performs. These
are:
1. Connect to a remote machine
2. Send data
3. Receive data
4. Close the connection
• A socket may not be connected to more than one host at a time.
• A socket may not reconnect after it's closed.

34
The java.net.Socket class
• The java.net.Socket class allows you to create socket
objects that perform all four fundamental socket
operations.
• You can connect to remote machines; you can send data;
you can receive data; you can close the connection.
• Each Socket object is associated with exactly one
remote host. To connect to a different host, you must
create a new Socket object.

35
Socket communication

• A server (program) runs on a specific computer and has


a socket that is bound to a specific port.
• The server waits and listens to the socket for a client to
make a connection request.

Connection request
port

Client
server

Fig. Client making connection request to server


36
Socket communication cont..

• If everything goes well, the server accepts the connection.


• Upon acceptance, the server gets a new socket bounds to a
different port. It needs a new socket (consequently a
different port number) so that it can continue to listen to the
original socket for connection requests while serving the
connected client.
port

server

port
Client
port Connection

Fig. Session established with temporary ports used for two way
communication
37
Constructing a Socket
• Connection is accomplished through the constructors.

• public Socket(String host, int port) throws UnknownHostException,


IOException
• public Socket(InetAddress address, int port) throws IOException

• public Socket(String host, int port, InetAddress localAddr, int


localPort) throws IOException
• public Socket(InetAddress address, int port, InetAddress localAddr,
int localPort) throws IOException

38
Opening socket

• The Socket() constructors do not just create a Socket object. They also attempt to
connect the underlying socket to the remote server.

• All the constructors throw an IOException if the connection can't be made for any
reason.

• You must at least specify the remote host and port to connect to.

• The host may be specified as either a string like "utopia.poly.edu" or as an


InetAddress object.

• The port should be an int between 1 and 65535.

• Socket webMetalab = new Socket("metalab.unc.edu", 80);

39
Scan port
• You cannot just connect to any port on any host. The remote host must actually be
listening for connections on that port.

• You can use the constructors to determine which ports on a host are listening for
connections.

public static void scan(InetAddress remote) {

String hostname = remote.getHostName();

for (int port = 0; port < 65536; port++) {

try { Socket s = new Socket(remote, port);

System.out.println("There is a server on port " + port + " of " + hostname);

s.close(); }catch (IOException e) { } }}

40
Choosing local port

• You can also specify a local port number,

• Setting the port to 0 tells the system to randomly choose an available port.

• If you need to know the port you're connecting from, you can always get it
with getLocalPort().

Socket webMetalab = new Socket("metalab.unc.edu", 80,


"calzone.oit.unc.edu", 0);

41
Socket methods

• There are methods to return information about the socket:

• InetAddress getInetAddress()
• InetAddress getLocalAddress()

• int getPort()//Returns the port the socket is bound to on the remote machine.

• int getLocalPort()//Returns the port the socket is bound to on the local


machine.
• public void connect(SocketAddress host, int timeout)

• String toString()

42
ServerSocket methods

1.public int getLocalPort()

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.

2. public Socket accept() throws IOException

Waits for an incoming client. This method blocks until either a client connects to the
server on the specified port or the socket times out, assuming that the time-out
value has been set using the setSoTimeout() method.Otherwise, this method blocks
indefinitely

43
ServerSocket methods cont..

3. public void setSoTimeout(int timeout)

Sets the time-out value for how long the server socket waits for a client during the
accept().

4. public void bind(SocketAddress host, int backlog)

Binds the socket to the specified server and port in the SocketAddress object.Use this
method if you instantiated the ServerSocket using the no-argument constructor.

44
Constructing Socket Objects
You need to at least specify the remote host and port you want to connect to.

Socket webSunsite = new Socket(“Localhost", 80);

Socket socket=new Socket(“localhost",80,“youraddress", portnumber);

• The latter constructors also specify the host and port you're connecting
from.

 On a system with multiple IP addresses, like many web servers, this


allows you to pick your network interface and IP address.

 you should probably set the port number then to use 0 which tells the
system to randomly choose an available port.

• The Socket() constructors create a Socket object & attempt to connect the
45
underlying socket to the remote server.
Socket Programming with TCP

• Server process must starting running before client process(Recall that TCP is not

connectionless).

• Client contacts the server by creating client-local socket specifying IP address and

port number of server process. Client TCP establishes connection to server TCP.

• When contacted by client, server TCP creates a new socket for server process to

communicate with client.

• Allows server to talk with multiple clients

• Source port numbers used to distinguish clients

• From application viewpoint: TCP provides reliable, in-order transfer of bytes (“pipe”)

between client and server. 46


Establishing a Simple Server Using Stream Sockets
Five steps to create a simple stream server in Java:
1. Open the Server Socket: Each client connection handled with a Socket object.
Server blocks until client connects.
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();

47
Establishing a Simple Client Using Stream Sockets

Four steps to create a simple stream client in Java:

1.Create a Socket Object: Obtains Socket’s InputStream and OutputStream.

Socket client = new Socket(server, port_id);

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();
48
Receiving and sending data
• Data is sent and received with output and input streams.
• There are methods to get an input stream for a socket and
an output stream for the socket.
public InputStream getInputStream() throws IOException
public OutputStream getOutputStream() throws
IOException
• There's also a method to close a socket.
public synchronized void close() throws IOException

49
Reading Input from a Socket
• The getInputStream() method returns an InputStream which reads data from the
socket.
• You can use all the normal methods of the InputStream class to read this data.
• Most of the time you'll chain the input stream to some other input stream or
reader object to more easily handle the data.
• Example
try {
Socket s = new Socket("metalab.unc.edu", 13);
InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
String theTime = br.readLine();
System.out.println(theTime);}
catch (IOException e) {
return (new Date()).toString();
50
Server Sockets

• A server socket binds to a particular port on the local machine.


• Once it has successfully bound to a port, it listens for incoming
connection attempts.
• When a server detects a connection attempt, it accepts the connection.
This creates a socket between the client and the server over which the
client and the server communicate.
• Multiple clients can connect to the same port on the server at the same
time.
• Incoming data is distinguished by the port to which it is addressed and
the client host and port from which it came.

51
Server Socket cont..
• The server can tell for which service (like http or ftp) the data is
intended by inspecting the port.
• It can tell which open socket on that service the data is intended for by
looking at the client address and port stored with the data.
• Incoming connections are stored in a queue until the server can accept
them.
• On most systems the default queue length is between 5 and 50.
• Once the queue fills up further incoming connections are refused until
space in the queue opens up.

52
The java.net.ServerSocket class

• The java.net.ServerSocket class represents a server socket.

• A ServerSocket object is constructed on a particular local port. Then it calls accept() to


listen for incoming connections.

• accept() blocks until a connection is detected. Then accept() returns a java.net.Socket


object that performs the actual communication with the client.

• There are three constructors that let you specify the port to bind to, the queue length for
incoming connections, and the IP address to bind to:
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress networkInterface)
throws IOException

53
Constructing server sockets

•Normally you only specify the port you want to listen on, like this:

try { ServerSocket ss = new ServerSocket(80); }

catch (IOException e) { System.err.println(e);}

•When a ServerSocket object is created, it attempts to bind to the port on the local host given by the port

argument.

•If another server socket is already listening to the port, then a java.net.BindException, a subclass of

IOException, is thrown.

•No more than one process or thread can listen to a particular port at a time. This includes non-Java processes or

threads.

•For example, if there's already an HTTP server running on port 80, you won't be able to bind to port 80.

54
Constructing server sockets cont..

•If you think you aren't going to be processing connections very quickly you may wish to

expand the queue when you construct the server socket. For example,

•try {

• ServerSocket httpd = new ServerSocket(80, 50);}

•catch (IOException e) { System.err.println(e);}

•Many hosts have more than one IP address.

•By default, a server socket binds to all available IP addresses on a given port.

•You can modify that behavior with this constructor:

•public ServerSocket(int port, int backlog, InetAddress bindAddr)throws IOException

55
Serving Multiple Clients
Multiple clients are quite often connected to a single server at the same
time. Typically, a server runs constantly on a server computer, and clients
from all over the Internet may want to connect to it. You can use threads
to handle the server's multiple clients simultaneously. Simply create a
thread for each connection.

56
Serving Multiple Clients
Here is how the server handles the establishment of a connection:

while (true) {

Socket socket = serverSocket.accept();

Thread thread = new ThreadClass(socket);

thread.start();}

The server socket can have many connections. Each iteration of the while
loop creates a new connection.

Whenever a connection is established, a new thread is created to handle


communication between the server and the new client; and this allows
multiple connections to run at the same time. 57
Example: Java server using TCP cont..

//create output stream attached to socket


DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
//read in line from the socket
clientSentence = inFromClient.readLine();
//process
capitalizedSentence = clientSentence.toUpperCase() + '\n';
//write out line to socket
outToClient.writeBytes(capitalizedSentence);
} }}

58
Socket Programming with UDP

• UDP (User Datagram Protocol)


• A connectionless protocol. because the packets have no relationship to
each other and because there is no state maintained.
• Allows packets of data (datagram) to be transmitted between
applications.
• Resembles mailing someone a letter
 The datagram packet is like a letter, where a client sends a
datagram to a server without actually connecting to the
server.
 This makes UDP an unreliable protocol.

59
Socket Programming with UDP cont..

• UDP does not guarantee that packets will be received in the order
they were sent or that they will even be delivered at all.
The java.net.DatagramPacket class –to send datagram packets
The java.net.DatagramSocket class – to receive datagram packets
• Sender does not wait for acknowledgements
• Arrival order is not guaranteed
• Arrival is not guaranteed.
• So why use UDP if it unreliable? Two reasons: speed and overhead.
• USED when speed is essential, even in cost of reliability
–e.g. Streaming Media, Games, Internet Telephony, etc.

60
Socket Programming with UDP cont..

• Datagram sockets transmit individual packets of information. This is


typically not appropriate for use by everyday programmers because
the transmission protocol is UDP (User Datagram Protocol).
• UDP provides a connectionless service. A connectionless service
does not guarantee that packets arrive at the destination in any
particular order.
• With UDP, packets can be lost or duplicated. Significant extra
programming is required on the programmer’s part to deal with these
problems.
• UDP is most appropriate for network applications that do not require
the error checking and reliability of TCP.

61
Socket Programming with UDP cont..

• Under UDP there is no “connection” between the server and the client.
There is no “handshaking”.
• The sender explicitly attaches the IP address and port of the destination to
each packet.
• The server must extract the IP address and port of the sender from the
received packet.
• From an application viewpoint, UDP provides unreliable transfer of
groups of bytes (“datagrams”) between client and server.

62
Steps to Receive a Datagram packet - UDP

1. Create an array of bytes large enough to hold the data of the incoming packet.

2. byte[] buffer = new byte[1024];


3. A DatagramPacket object is instantiated using the array of bytes.
4. DatagramPacket packet =new DatagramPacket(buffer, buffer.length);
5. A DatagramSocket is instantiated, and it is specified which port (and specific
localhost address, if necessary) on the localhost the socket will bind to.
DatagramSocket socket = new DatagramSocket(1234);
6. The receive() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object. This causes the thread to block until a datagram packet is
received or a time out occurs.
socket.receive(packet);
InetAddress remoteHost = packet.getAddress();
int remotePort = packet.getPort();
byte[] data = packet.getData();

63
Steps to Send a Datagram packet - UDP

1. Create an array of bytes large enough to hold the data of the packet to be sent, and fill the array with

the data.

2. byte[] buffer = new byte[1024];

2. Create a new DatagramPacket object that contains the array of bytes, as well as the server name and

port number of the recipient.

InetAddress host =InetAddress.getByName(“www.mysite.com");

DatagramPacket packet =new DatagramPacket(buffer, buffer.length, host, 1234);

3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost address, if

necessary) on the localhost the socket will bind to.

DatagramSocket socket = new DatagramSocket();

4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket object.
64
The End
65

You might also like