Web Tecw2
Web Tecw2
Tushar B. Kute,
Department of Information Technology,
Sandip Institute of Technology and
Research Centre, Nashik.
Agenda
• Networking Basics
– TCP, UDP, Ports, DNS, Client-Server Model
• TCP/IP in Java
• Sockets
• URL
– The java classes: URL, URLConnection
• Datagrams
2
“The Network is Computer”
PC client
Internet
Server
Local Area Network
PDA
Increased demand for Internet applications
st
ue
q
Re
Client
Server
Network
Re
s ul
t
Client machine
Server machine
Networking Basics
• Computers running on the Internet communicate with
each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP)
6
DNS - Domain name system
• The Domain Name system (DNS) associates various sorts
of information with so-called domain names.
• Most importantly, it serves as the "phone book" for the
Internet by translating human-readable computer
hostnames, e.g. www.example.com, into the IP
addresses, e.g. 208.77.188.166, that networking
equipment needs to deliver information.
• It also stores other information such as the list of mail
exchange servers that accept email for a given domain.
7
Understanding Ports
• The TCP and UDP P
o TCP
protocols use ports to server
r Client
map incoming data to a t
particular process
running on a computer.
TCP or UDP
Packet
Data port# data
Understanding Ports
• Port is represented by a positive (16-bit) integer
value
• Some ports have been reserved to support common/
well known services:
– ftp 21/tcp
– telnet 23/tcp
– smtp 25/tcp
– login 513/tcp
• User level process/services generally use port
number value >= 1024
Sockets
• Sockets provide an interface for programming networks at
the transport layer.
• Network communication using Sockets is very much similar to
performing file I/O
– In fact, socket handle is treated like file handle.
– The streams used in file I/O operation are also applicable to socket-
based I/O
• Socket-based communication is programming language
independent.
– That means, a socket program written in Java language can also
communicate to a program written in Java or non-Java socket
program.
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
server
Client
Socket Communication
• 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
Transmission Control Protocol
• A connection-based protocol that provides a reliable
flow of data between two computers.
• Provides a point-to-point channel for applications that
require reliable communications.
– The Hypertext Transfer Protocol (HTTP), File Transfer Protocol
(FTP), and Telnet are all examples of applications that require a
reliable communication channel
• 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.
User Datagram Protocol
• A protocol that sends independent packets of data,
called datagrams, from one computer to another with
no guarantees about arrival. UDP is not connection-
based like TCP and is not reliable:
– Sender does not wait for acknowledgements
– Arrival order is not guaranteed
– Arrival is not guaranteed
• Used when speed is essential, even in cost of reliability
– e.g. streaming media, games, Internet telephony, etc.
Ports
• Data transmitted over the Internet is
accompanied by addressing information that
identifies the computer and the port for which
it is destined.
– The computer is identified by its 32-bit IP address,
which IP uses to deliver data to the right
computer on the network. Ports are identified by
a 16-bit number, which TCP and UDP use to
deliver the data to the right application.
Ports – Cont.
• Port numbers range from 0 to 65,535 (16-bit)
– Ports 0 - 1023 are called well-known ports. They
are reserved for use by well-known services:
• 20, 21: FTP
• 23: TELNET
• 25: SMTP
• 110: POP3
• 80: HTTP
Networking Classes in the JDK
• Through the classes in java.net, Java programs
can use TCP or UDP to communicate over the
Internet.
– The URL, URLConnection, Socket, and
ServerSocket classes all use TCP to
communicate over the network.
– The DatagramPacket, DatagramSocket,
and MulticastSocket classes are for use with
UDP.
17
TCP/IP in Java
• Accessing TCP/IP from Java is straightforward.
The main functionality is in the following
classes:
– java.net.InetAddress : Represents an IP
address (either IPv4 or IPv6) and has methods for
performing DNS lookup (next slide).
– java.net.Socket : Represents a TCP socket.
– java.net.ServerSocket : Represents a
server socket which is capable of waiting for
requests from clients.
18
InetAddress
• The InetAddress class is used to encapsulate
both the numerical IP address and the domain
name for that address.
• We interact with this class by using the name
of an IP host, which is more convenient and
understandable than its IP address.
• The InetAddress class hides the number
inside.
Factory Methods
• static InetAddress getLocalHost( )
throws UnknownHostException
• static InetAddress getByName(String hostName)
throws UnknownHostException
• static InetAddress[ ] getAllByName(String
hostName)
throws UnknownHostException
Example:
class InetAddressTest
{
public static void main(String args[])
throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.tusharkute.com");
System.out.println(Address);
InetAddress SW[] =
InetAddress.getAllByName("www.yahoo.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Instance Methods
class InetAddressTest1
{
public static void main(String args[])
throws UnknownHostException
{
InetAddress Address =
InetAddress.getByName("www.google.com");
System.out.println(Address.getHostAddress());
System.out.println(Address.getHostName());
if(Address.isMulticastAddress())
System.out.println("It is multicast address");
}
}
Sockets and Java Socket Classes
• A socket is an 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 destined to be sent.
• Java’s .net package provides two classes:
– Socket – for implementing a client
– ServerSocket – for implementing a server
23
Java Sockets
Server ServerSocket(1234)
Input/read stream
Socket(“128.250.25.158”, 1234)
25
Constructors
• Socket(String remoteHost, int remotePort)
http://www.javapassion.com:80/javaintro/index.html#Networking_A
Protocol
38
Constructors
• URL(String urlSpecifier)
• URL(URL urlObj, String urlSpecifier)
• URL(String protName, String hostName, int
port, String path)
• URL(String protName, String hostName, String
path)
39
Example
class URLDemo
{
public static void main(String args[])
throws MalformedURLException
{
URL hp = new URL("http://content-
ind.cricinfo.com/ci/content/current/story/news.html");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
Output
Protocol: http
Port: -1
Host: content-ind.cricinfo.com
File: /ci/content/current/story/news.html
Ext:http://content-
ind.cricinfo.com/ci/content/current/story/news.
html
URLConnection
• URLConnection is an abstract class that represents an active
connection to a resource specified by a URL.
• The URLConnection class has two different but related
purposes. First, it provides more control over the interaction
with a server (especially an HTTP server) than the URL class.
With a URLConnection, we can inspect the header sent by the
server and respond accordingly. We can set the header fields
used in the client request. We can use a URLConnection to
download binary files.
• Finally, a URLConnection lets us send data back to a web
server with POST or PUT and use other HTTP request
methods.
Process
• Construct a URL object.
• Invoke the URL object's openConnection( ) method
to retrieve a URLConnection object for that URL.
• Configure the URLConnection.
• Read the header fields.
• Get an input stream and read data.
• Get an output stream and write data.
• Close the connection.
Reading Data from Server
• Construct a URL object.
• Invoke the URL object's openConnection( ) method to
retrieve a URLConnection object for that URL.
• Invoke the URLConnection's getInputStream( ) method.
• Read from the input stream using the usual stream API.
• The getInputStream() method returns a generic
InputStream that lets you read and parse the data that
the server sends.
• public InputStream getInputStream( )
Example
public class SourceViewer2 {
public static void main (String[] args) {
if (args.length > 0) {
try {
//Open the URLConnection for reading
URL u = new URL(args[0]);
URLConnection uc = u.openConnection( );
InputStream raw = uc.getInputStream( );
InputStream buffer = new BufferedInputStream(raw);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(buffer);
int c;
while ((c = r.read( )) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a parseable URL");
}
catch (IOException ex) {
System.err.println(ex);
}
} // end if
} // end main
} // end SourceViewer2
URLConnection Example
import java.net.*;
import java.io.*;
46
Difference between URL and URLConnection
53
TCP vs. UDP
No. TCP UDP
1 This Connection oriented protocol This is connection-less protocol
The TCP connection is byte stream The UDP connection is a message stream
2