Advanced Java Programming TCP/IP networking in Java
Download
Report
Transcript Advanced Java Programming TCP/IP networking in Java
Gareth
Lee
John
Morris
Advanced Java Programming
Unit One: Networking
Gareth Lee
Department of Electrical and Electronic Engineering,
University of Western Australia
Overview
•
•
•
•
•
Java’s network support
Addressing other machines
Communicating using TCP/IP
Communicating using UDP
Broadcasting and multicasting
Recommended Reading
• Java Network Programming, Elliotte Rusty
Harold, O’Reilly and Associates, 1997,
ISBN 1-56592-227-1
• TCP/IP Network Administration, Second
Edition, Craig Hunt, O’Reilly and
Associates, 1997, ISBN 1-56592-322-7
• The Java Developer’s connection:
http://www.javasoft.com/jdc
• The Javadoc documentation
Network Programming
• Mechanisms by which software running on
two or more computational devices can
exchange messages
• Desktop Computers
• PDAs / Set Top Boxes / Mobile Telephones?
• Java is a network centric programming
language
• Java abstracts details of network
implementation behind a standard API
• Portable (and future proof) . . .
• but may be rather limiting
A programming model for network
communications
Java APIs
HTTP/FTP/etc...
1:1 or 1:Many
TCP, UDP
Internet Protocol
Applications
Application Protocols
Unicast Broadcast Multicast
Streams
Java & IP don’t care
Dealt with in this Unit One.
Dealt with in this Unit Two.
Datagrams
Addressing & Routing
Physical Transport
Internet Protocol (IPv4)
• Abstracts away the details of the physical
network implementations (such as
Ethernet, Token Ring, ATM, Sonet)
• All traffic uses the same rules to move
from machine to machine
• Easy to write programs
• Easy to build network hardware
• Works with Datagrams: small discrete
packets of data (rather like a letter)
Internet Protocol (IPv4)
• A way of uniquely addressing machines
using 32 bit addresses: giving 4 billion
possible addresses (like a zip code)
• A system for numbering ports on each
machine (like a post office box)
• Port numbers allow several services to
operate from a machine at the same time
Common well known ports
•
•
•
•
•
•
•
Ports 20/21 File Transfer Protocol
Port 23
Telnet
Port 25
Simple Mail Transport Proto.
Port 79
Finger
Port 80
HTTP
Port 110
POP3 (Post Office Protocol)
All well known ports in the range 1..1023
Internet Protocol (IPv4)
• The Internet consists of a large number of
independent sub-networks (subnets)
• A mechanism for relaying datagrams from
one network to another (routing)
• For routing to work each organisation
must have a well known prefix (all UWA
addresses start with the bytes 130.95)
• . . but we don’t use addresses very
efficiently and we’re running out fast (UWA
doesn’t need 65536 separate addresses)
Next Generation Internet
• The solution is IPv6 which uses 128 bit
addresses
• Improves services such as multicasting
and secure communication
• Several addresses per m2 of the Earth’s
surface (3.4 x 1038 to be precise)
• Not yet widely deployed by ISPs
• Perhaps widely deployed in 2-4 years
• Well written Java software should move to
IPv6 without modification/recompilation
• One benefit of abstracted APIs
IP Addresses and Java
• Java has a class java.net.InetAddress
which abstracts network addresses
• Serves three main purposes:
• Encapsulates an address
• Performs name lookup (converting a host name
into an IP address)
• Performs reverse lookup (converting the
address into a host name)
java.net.InetAddress (1)
• Abstraction of a network address
• Currently uses IPv4 (a 32 bit address)
• Will support other address formats in
future
• Allows an address to be obtained from a
host name and vice versa
• Is immutable (is a read-only object)
• Create an InetAddress object with the address
you need and throw it away when you have
finished
java.net.InetAddress (2)
• Static construction using a factory method
• InetAddress getByName(String hostName)
• hostName can be “host.domain.com.au”, or
• hostName can be “130.95.72.134”
• InetAddress getLocalHost()
• Some useful methods:
• String getHostName()
• Gives you the host name (for example “www.sun.com”)
• String getHostAddress()
• Gives you the address (for example “192.18.97.241”)
• InetAddress getLocalHost()
• InetAddress[] getAllByName(String hostName)
Using InetAddress objects
import java.net.InetAddress;
import java.net.UnknownHostExcepion;
public static void main(String[] args)
{
try {
InetAddress inet1 =
InetAddress.getByName("asp.ee.uwa.edu.au");
System.out.println(
"HostAddress=" + inet1.getHostAddress());
InetAddress inet2 =
InetAddress.getByName("130.95.72.134");
System.out.println("HostName=" + inet2.getHostName());
if (inet1.equals(inet2))
System.out.println("Addresses are equal");
}
catch (UnknownHostException uhe) {
uhe.printStackTrace();
}
}
Transmission Control Protocol
• TCP is built on top of IP
• Provides the illusion of a continuous flow
(or stream) of data between sender and
receiver (rather like a telephone call)
• Splits up streams into strings of small
datagrams which are sent in succession
• Contains an error recovery mechanism to
recover datagrams which are lost
• These features make application
development simpler and so it is widely
used
Transmission Control Protocol
• Used by FTP / Telnet / Finger and
numerous other network applications
• Used by stream oriented servers such as
HTTP (as we will see in unit 2)
• Can also be used to provide inter-process
communications (IPC) between the
applications on a single machine (such as
a X-windows clients and servers)
Two types of TCP Socket
• java.net.ServerSocket is used by servers
so that they can accept incoming TCP/IP
connections
• A server is a piece of software which advertises
and then provides some service on request
• java.net.Socket is used by clients who
wish to establish a connection to a
(remote) server
• A client is a piece of software (usually on a
different machine) which makes use of some
service
java.net.ServerSocket (1)
• Listens on well-known port for incoming
connections
• Creates a dynamically allocated port for
each newly established connection
• Provides a Socket connected to the new
port
• Maintains a queue to ensure that
prospective clients are not lost
java.net.ServerSocket (2)
• Construction:
• ServerSocket(int port, int backlog)
• Allows up to backlog requests to queue waiting for the
server to deal with them
• Some useful methods:
• Socket accept()
• Blocks waiting for a client to attempt to establish a
connection
• void close()
• Called by the server when it is shutting down to ensure
that any resources are deallocated
• More details in the Javadoc (as always!)
java.net.Socket (1)
• Provides access to TCP/IP streams
• Bi-directional communication between
sender and receiver
• Can be used to connect to a remote
address and port by using the constructor:
• Socket(String remoteHost, int port)
• Also used to accept an incoming
connection (see ServerSocket)
java.net.Socket (2)
• Can obtain access to input and output
streams
• Input stream allows reception of data from
the other party
• InputSteam getInputStream()
• Output stream allows dispatch of data to
the other party
• OutputStream getOutputStream()
How it all fits together
Client (sid)
s = new Socket
(“fred”, 80)
Server (fred)
2037
80
2037
1583
s.getInputStream() 2037
s.getOuputStream()
ServerSocket ss.
s = ss.accept()
Socket s
1583 s.getInputStream()
s.getOuputStream()
A sample TCP server
public static void main(String[] args)
{
try {
ServerSocket agreedPort =
new ServerSocket(AGREED_PORT_NUMBER, 5);
while (isStillServing()) {
Socket session = agreedPort.accept();
respond(session);
session.close();
}
agreedPort.close();
}
catch
//
}
catch
//
}
}
(UnknownHostException uhe) {
Very unlikely to occur
(IOException ioe) {
May occur if the client misbehaves?
A sample TCP client
public static void main(String[] args)
{
try {
InetAddress server = InetAddress.getByName(args[0]);
Socket connection =
new Socket(server, AGREED_PORT_NUMBER);
makeRequestToServer(connection);
getReplyFromServer(connection);
connection.close();
}
catch (UnknownHostException uhe) {
// arg[0] is not a valid server name or IP address
}
catch (IOException ioe) {
// The connection to the server failed somehow:
// the server might have crashed mid sentence?
}
}
What are datagrams?
• Datagrams are discrete packets of data
• Each is like a parcel that can be addressed
and sent to an recipient anywhere on the
Internet
• This is abstracted as the User Datagram
Protocol (UDP) in RFC768 (August 1980)
• Most networks cannot guarantee reliable
delivery of datagrams
Why use datagrams?
• Good for sending data that can naturally
be divided into small chunks
• Poor for (lossless) stream based
communications
• Makes economical use of network
bandwidth (up to 3 times the efficiency of
TCP/IP for small messages)
• Datagrams can be locally broadcast or
multicast (one-to-many communication)
Application using datagrams
• UDP can be used for economical point-topoint communications over LANs
• Unix NFS (Network File System)
• NIS (a.k.a. Yellow Pages)
• Datagrams can be used for one-to-many
communication:
• Local network broadcasting;
• Multicasting (MBONE)
• but there is no way to create one-to-many
streams using TCP/IP
java.net.DatagramPacket (1)
• DatagramPackets normally used as short
lived envelopes for datagram messages:
• Used to assemble messages before they are
dispatched onto the network,
• or dismantle messages after they have been
received
• Has the following attributes:
•
•
•
•
Destination/source address
Destination/source port number
Data bytes constituting the message
Length of message data bytes
java.net.DatagramPacket (2)
• Construction:
• DatagramPacket(byte[] data, int length)
• Some useful methods:
•
•
•
•
void setAddress(InetAddress addr)
InetAddress getAddress()
void setPort(int port)
int getPort()
• DatagramPackets are not immutable so, in
principle you can reuse then, but . .
• Experience has shown that they often
misbehave when you do -- create a new
one, use it once, throw it away!
java.net.DatagramSocket (1)
• Used to represent a socket associated with
a specific port on the local host
• Used to send or receive datagrams
• Note: there is no counterpart to
java.net.ServerSocket! Just use a
DatagramSocket with a agreed port
number so others know which address and
port to send their datagrams to
java.net.DatagramSocket (2)
• Construction:
• DatagramSocket(int port)
• Uses a specified port (used for receiving datagrams)
• DatagramSocket()
• Allocate any available port number (for sending)
• Some useful methods:
• void send(DatagramPacket fullPacket)
• Sends the full datagram out onto the network
• void receive(DatagramPacket emptyPacket)
• Waits until a datagram and fills in emptyPacket with the
message
• . . . and a few more in the Javadoc
sea.datagram.DatagramSender
• This example sends datagrams to a
specific host (anywhere on the Internet)
• The steps are as follows:
• Create a new DatagramPacket
• Put some data which constitutes your message
in the new DatagramPacket
• Set a destination address and port so that the
network knows where to deliver the datagram
• Create a socket with a dynamically allocated
port number (if you are just sending from it)
• Send the packet through the socket onto the
network
sea.datagram.DatagramSender
byte[] data = “This is the message”.getBytes();
DatagramPacket packet =
new DatagramPacket(data, data.length);
// Create an address
InetAddress destAddress =
InetAddress.getByName(“fred.domain.com”);
packet.setAddress(destAddress);
packet.setPort(9876);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
sea.datagram.DatagramReceiver
• The steps are the reserve of sending:
• Create an empty DatagramPacket (and allocate
a buffer for the incoming data)
• Create a DatagramSocket on an agreed socket
number to provide access to arrivals
• Use the socket to receive the datagram (the
thread will block until a new datagram arrrives)
• Extract the data bytes which make up the
message
sea.datagram.DatagramReceiver
// Create an empty packet with some buffer space
byte[] data = new byte[1500];
DatagramPacket packet =
new DatagramPacket(data, data.length);
DatagramSocket socket = new DatagramSocket(9876);
// This call will block until a datagram arrives
socket.receive(packet);
// Convert the bytes back into a String and print
String message =
new String(packet.getData(), 0, packet.getLength());
System.out.println("message is " + message);
System.out.println("from " + packet.getAddress());
But it’s never quite that simple!
• Several of the constructors/methods throw
exceptions which I have omitted
• Each datagrams can only hold up to a
maximum of 64KB of data . .
• . . but the underlying transport layer may
split the message into smaller packets (for
instance Ethernet uses about 1500 bytes)
• Always remember that UDP is an
unreliable protocol: If any of the split
datagrams are lost the whole message will
be lost
Broadcasting
• Broadcasting allows a single datagram to
be sent to a group of listeners
• The group consists of all the computers
within the local network
• The previous code examples can be used
for broadcasting
• Just change the address: each network
has a unique broadcast address
IP addresses revisited
• Each 32 bit IP number consists of two
components:
• The network address
• The unique international address of the
network
• The host address
• The unique address of a specific host in the
net
• There are three classes of network
address denoted class ‘A’, ‘B’ and ‘C’
Class A,B and C addresses
192
Class A
0...
Class B
10...
Class C
110...
.
85
.
35
.
Network Address Byte
Host Address Byte
87
Broadcast addresses
• CIIPS has a class ‘C’ network which has
the address 130.95.72
• This portable computer has host address
134 within the CIIPS network
• Each network has a single host address
which is set aside for broadcasts (either all
one bits or all zero bits)
• The CIIPS network uses broadcast address
130.95.72.255
• Broadcasts are never routed onto other
networks
Multicasting (1)
• Described in RFC1112 (August 1989)
• Multicasting allows distribution of a
datagram to a group of listeners who are
not within the local network
• Routers between networks need to pass
multicast datagrams. . but many do not!
• The MBONE is a way of tunneling
datagrams across the Internet between
islands of multicast activity
Multicasting (2)
• Multicasts are also sent to a special
address (known as a “group”)
• Multicast groups need to be agreed in
advance. They are not derived from a
specific network/host address
• Multicast groups identify a subject area (or
stream of content) rather than a specific
computer or network. They are more like a TV
channel number than a telephone number.
• The IETF has set aside addresses from
224.0.0.1 to 239.255.255.255 specifically for
multicasting
Multicasting (3)
• To send to (or receive from) a multicast
group it is first necessary to register
interest in the group
• This results in an Internet Group Management
Protocol (IGMP) message being sent to your
router (RFCs 988/1112/2236)
• Then a datagram is created, addressed to
the group (and the chosen port)
• Java has a specialised socket for
multicasting: java.net.MulticastSocket
Some multicast groups
•
•
•
•
•
•
224.0.0.1
All hosts within local subnet
224.0.1.7
Audio news multicast
224.0.1.12
Video from IETF meetings
224.0.1.20
Expts. within local subnet
224.0.1.25
NBC Professional News
There are 268 million multicast addresses
(in IPv4) with 65 thousand ports in each!
java.net.MulticastSocket
• Subclass of java.net.DatagramSocket
• Constructed the same way
• Adds some extra methods:
• void joinGroup(InetAddress mcastGroup)
• Enter the specifies group so that you can send or receive
datagrams
• void leaveGroup(InetAddress mcastGroup)
• Leave a group that you previously joined
• void setTimeToLive(int ttl)
• Sets how far your datagrams will travel before routers
ignore them
• int getTimeToLive()
sea.datagram.MulticastSender
• Sending similar to the previous example. .
• . . .but must register with the multicast
group and decide the longevity
• The steps involved are:
•
•
•
•
•
Create the MulticastSocket.
Join the multicast group(s) (on startup).
Create the DatagramPacket.
Send the packet through the socket.
Leave the multicast group (on exit).
sea.datagram.MulticastSender
InetAddress multicastGroup =
InetAddress.getByName(multicastGroupAddr);
MulticastSocket socket = new MulticastSocket();
socket.joinGroup(multicastGroup);
socket.setTimeToLive(5);
byte[] data = “This is the message”.getBytes();
DatagramPacket datagram =
new DatagramPacket(data, data.length);
datagram.setAddress(multicastGroup);
datagram.setPort(9876);
socket.send(datagram);
socket.leaveGroup(multicastGroup);
sea.datagram.MulticastReceiver
• The steps are:
•
•
•
•
Create a multicast socket on an agreed port.
Join the multicast group (on startup).
Create an empty datagram.
Wait for datagram to be delivered on the
socket.
• Unpack and use the datagram.
• Leave the multicast group (on exit).
sea.datagram.MulticastReceiver
InetAddress multicastGroup =
InetAddress.getByName(multicastGroupAddr);
MulticastSocket socket = new MulticastSocket(9876);
socket.joinGroup(multicastGroup);
byte[] data = new byte[1000];
DatagramPacket packet =
new DatagramPacket(data, data.length);
socket.receive(packet);
String message = new String(
packet.getData(), 0, packet.getLength());
socket.leaveGroup(multicastGroup);
Useful sources of information
• The Internet Engineering Task Force (IETF)
which is at http://www.ietf.org -- you will be
able to download RFCs from here
• Multicasting try reading the HOWTO which
is available from the URL:
http://ftp.southcom.com.au/LDP/HOWTO/...
Multicast-HOWTO.html
Homework
• Read through the code samples to
convince yourself you understand what’s
going on
• Sample code can be downloaded from
http://ciips.ee.uwa.edu.au/~gareth
• If you can, run the examples
Comments, Suggestions. . .
• How was the presentation paced?
• Was there enough (or too much) technical
content?
• Any areas of particular interest?
• Comments regarding presentation style?