Professional Documents
Culture Documents
Introduction
1
Introduction
2
Introduction cont’d…
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
st
e
qu
Client
Re Server
Network
Re
su
l t
Client machine
Server machine
7
What is Internet protocol(ip)
8
The InetAddress Class in java
9
The InetAddress Class in java cont..
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
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
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..
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..
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
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?
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..
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.
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
Connection request
port
Client
server
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.
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.
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.
40
Choosing local port
• 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().
41
Socket methods
• InetAddress getInetAddress()
• InetAddress getLocalAddress()
• int getPort()//Returns the port the socket is bound to on the remote machine.
• String toString()
42
ServerSocket methods
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.
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..
Sets the time-out value for how long the server socket waits for a client during the
accept().
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.
• The latter constructors also specify the host and port you're connecting
from.
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
• From application viewpoint: TCP provides reliable, in-order transfer of bytes (“pipe”)
47
Establishing a Simple Client Using Stream Sockets
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
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
• 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:
•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 {
•By default, a server socket binds to all available IP addresses on a given port.
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) {
thread.start();}
The server socket can have many connections. Each iteration of the while
loop creates a new connection.
58
Socket Programming with UDP
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..
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.
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. Create a new DatagramPacket object that contains the array of bytes, as well as the server name and
3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost address, if
4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket object.
64
The End
65