Скачать презентацию Gareth Lee John Morris Advanced Java Programming Unit Скачать презентацию Gareth Lee John Morris Advanced Java Programming Unit

9f4c1921d80d93ce9c3b88a868f3ad85.ppt

  • Количество слайдов: 52

Gareth Lee John Morris Advanced Java Programming Unit One: Networking Gareth Lee Department of 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 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 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 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 A programming model for network communications Java APIs HTTP/FTP/etc. . . 1: 1 or 1: Many TCP, UDP Applications Application Protocols Unicast Broadcast Multicast Streams Internet Protocol Java & IP don’t care Dealt with in this Unit One. Dealt with in this Unit Two. Datagrams Addressing & Routing Physical Transport

Internet Protocol (IPv 4) • Abstracts away the details of the physical network implementations Internet Protocol (IPv 4) • 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 (IPv 4) • A way of uniquely addressing machines using 32 bit Internet Protocol (IPv 4) • 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 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 POP 3 (Post Office Protocol) All well known ports in the range 1. . 1023

Internet Protocol (IPv 4) • The Internet consists of a large number of independent Internet Protocol (IPv 4) • 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 IPv 6 which uses 128 bit addresses Next Generation Internet • The solution is IPv 6 which uses 128 bit addresses • Improves services such as multicasting and secure communication • Several addresses per m 2 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 IPv 6 without modification/recompilation • One benefit of abstracted APIs

IP Addresses and Java • Java has a class java. net. Inet. Address which IP Addresses and Java • Java has a class java. net. Inet. Address 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. Inet. Address (1) • Abstraction of a network address • Currently uses java. net. Inet. Address (1) • Abstraction of a network address • Currently uses IPv 4 (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 Inet. Address object with the address you need and throw it away when you have finished

java. net. Inet. Address (2) • Static construction using a factory method • Inet. java. net. Inet. Address (2) • Static construction using a factory method • Inet. Address get. By. Name(String host. Name) • host. Name can be “host. domain. com. au”, or • host. Name can be “ 130. 95. 72. 134” • Inet. Address get. Local. Host() • Some useful methods: • String get. Host. Name() • Gives you the host name (for example “www. sun. com”) • String get. Host. Address() • Gives you the address (for example “ 192. 18. 97. 241”) • Inet. Address get. Local. Host() • Inet. Address[] get. All. By. Name(String host. Name)

Using Inet. Address objects import java. net. Inet. Address; import java. net. Unknown. Host. Using Inet. Address objects import java. net. Inet. Address; import java. net. Unknown. Host. Excepion; public static void main(String[] args) { try { Inet. Address inet 1 = Inet. Address. get. By. Name("asp. ee. uwa. edu. au"); System. out. println( "Host. Address=" + inet 1. get. Host. Address()); Inet. Address inet 2 = Inet. Address. get. By. Name("130. 95. 72. 134"); System. out. println("Host. Name=" + inet 2. get. Host. Name()); if (inet 1. equals(inet 2)) System. out. println("Addresses are equal"); } catch (Unknown. Host. Exception uhe) { uhe. print. Stack. Trace(); } }

Transmission Control Protocol • TCP is built on top of IP • Provides the 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 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. Server. Socket is used by servers Two types of TCP Socket • java. net. Server. Socket 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. Server. Socket (1) • Listens on well-known port for incoming connections • java. net. Server. Socket (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. Server. Socket (2) • Construction: • Server. Socket(int port, int backlog) • java. net. Server. Socket (2) • Construction: • Server. Socket(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 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 remote. Host, int port) • Also used to accept an incoming connection (see Server. Socket)

java. net. Socket (2) • Can obtain access to input and output streams • java. net. Socket (2) • Can obtain access to input and output streams • Input stream allows reception of data from the other party • Input. Steam get. Input. Stream() • Output stream allows dispatch of data to the other party • Output. Stream get. Output. Stream()

How it all fits together Client (sid) Server (fred) 80 2037 s = new How it all fits together Client (sid) Server (fred) 80 2037 s = new Socket (“fred”, 80) 2037 1583 Server. Socket ss. s = ss. accept() Socket s s. get. Input. Stream() s. get. Ouput. Stream() 2037 1583 s. get. Input. Stream() s. get. Ouput. Stream()

A sample TCP server public static void main(String[] args) { try { Server. Socket A sample TCP server public static void main(String[] args) { try { Server. Socket agreed. Port = new Server. Socket(AGREED_PORT_NUMBER, 5); while (is. Still. Serving()) { Socket session = agreed. Port. accept(); respond(session); session. close(); } agreed. Port. close(); } catch // } } (Unknown. Host. Exception uhe) { Very unlikely to occur (IOException ioe) { May occur if the client misbehaves?

A sample TCP client public static void main(String[] args) { try { Inet. Address A sample TCP client public static void main(String[] args) { try { Inet. Address server = Inet. Address. get. By. Name(args[0]); Socket connection = new Socket(server, AGREED_PORT_NUMBER); make. Request. To. Server(connection); get. Reply. From. Server(connection); connection. close(); } catch (Unknown. Host. Exception 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 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 RFC 768 (August 1980) • Most networks cannot guarantee reliable delivery of datagrams

Why use datagrams? • Good for sending data that can naturally be divided into 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 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. Datagram. Packet (1) • Datagram. Packets normally used as short lived envelopes java. net. Datagram. Packet (1) • Datagram. Packets 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. Datagram. Packet (2) • Construction: • Datagram. Packet(byte[] data, int length) • java. net. Datagram. Packet (2) • Construction: • Datagram. Packet(byte[] data, int length) • Some useful methods: • • void set. Address(Inet. Address addr) Inet. Address get. Address() void set. Port(int port) int get. Port() • Datagram. Packets 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. Datagram. Socket (1) • Used to represent a socket associated with a java. net. Datagram. Socket (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. Server. Socket! Just use a Datagram. Socket with a agreed port number so others know which address and port to send their datagrams to

java. net. Datagram. Socket (2) • Construction: • Datagram. Socket(int port) • Uses a java. net. Datagram. Socket (2) • Construction: • Datagram. Socket(int port) • Uses a specified port (used for receiving datagrams) • Datagram. Socket() • Allocate any available port number (for sending) • Some useful methods: • void send(Datagram. Packet full. Packet) • Sends the full datagram out onto the network • void receive(Datagram. Packet empty. Packet) • Waits until a datagram and fills in empty. Packet with the message • . . . and a few more in the Javadoc

sea. datagram. Datagram. Sender • This example sends datagrams to a specific host (anywhere sea. datagram. Datagram. Sender • This example sends datagrams to a specific host (anywhere on the Internet) • The steps are as follows: • Create a new Datagram. Packet • Put some data which constitutes your message in the new Datagram. Packet • 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. Datagram. Sender byte[] data = “This is the message”. get. Bytes(); Datagram. sea. datagram. Datagram. Sender byte[] data = “This is the message”. get. Bytes(); Datagram. Packet packet = new Datagram. Packet(data, data. length); // Create an address Inet. Address dest. Address = Inet. Address. get. By. Name(“fred. domain. com”); packet. set. Address(dest. Address); packet. set. Port(9876); Datagram. Socket socket = new Datagram. Socket(); socket. send(packet);

sea. datagram. Datagram. Receiver • The steps are the reserve of sending: • Create sea. datagram. Datagram. Receiver • The steps are the reserve of sending: • Create an empty Datagram. Packet (and allocate a buffer for the incoming data) • Create a Datagram. Socket 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. Datagram. Receiver // Create an empty packet with some buffer space byte[] sea. datagram. Datagram. Receiver // Create an empty packet with some buffer space byte[] data = new byte[1500]; Datagram. Packet packet = new Datagram. Packet(data, data. length); Datagram. Socket socket = new Datagram. Socket(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. get. Data(), 0, packet. get. Length()); System. out. println("message is " + message); System. out. println("from " + packet. get. Address());

But it’s never quite that simple! • Several of the constructors/methods throw exceptions which 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 64 KB 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 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: • 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 . 35 . 10. . Class A, B and C addresses 192 Class A . 35 . 10. . . Class C 85 0. . . Class B . 110. . . Network Address Byte Host Address Byte 87

Broadcast addresses • CIIPS has a class ‘C’ network which has the address 130. 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 RFC 1112 (August 1989) • Multicasting allows distribution of Multicasting (1) • Described in RFC 1112 (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 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 specifically for multicasting

Multicasting (3) • To send to (or receive from) a multicast group it is 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. Multicast. Socket

Some multicast groups • • • 224. 0. 0. 1 All hosts within local 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 IPv 4) with 65 thousand ports in each!

java. net. Multicast. Socket • Subclass of java. net. Datagram. Socket • Constructed the java. net. Multicast. Socket • Subclass of java. net. Datagram. Socket • Constructed the same way • Adds some extra methods: • void join. Group(Inet. Address mcast. Group) • Enter the specifies group so that you can send or receive datagrams • void leave. Group(Inet. Address mcast. Group) • Leave a group that you previously joined • void set. Time. To. Live(int ttl) • Sets how far your datagrams will travel before routers ignore them • int get. Time. To. Live()

sea. datagram. Multicast. Sender • Sending similar to the previous example. . • . sea. datagram. Multicast. Sender • Sending similar to the previous example. . • . . . but must register with the multicast group and decide the longevity • The steps involved are: • • • Create the Multicast. Socket. Join the multicast group(s) (on startup). Create the Datagram. Packet. Send the packet through the socket. Leave the multicast group (on exit).

sea. datagram. Multicast. Sender Inet. Address multicast. Group = Inet. Address. get. By. Name(multicast. sea. datagram. Multicast. Sender Inet. Address multicast. Group = Inet. Address. get. By. Name(multicast. Group. Addr); Multicast. Socket socket = new Multicast. Socket(); socket. join. Group(multicast. Group); socket. set. Time. To. Live(5); byte[] data = “This is the message”. get. Bytes(); Datagram. Packet datagram = new Datagram. Packet(data, data. length); datagram. set. Address(multicast. Group); datagram. set. Port(9876); socket. send(datagram); socket. leave. Group(multicast. Group);

sea. datagram. Multicast. Receiver • The steps are: • • • Create a multicast sea. datagram. Multicast. Receiver • 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. Multicast. Receiver Inet. Address multicast. Group = Inet. Address. get. By. Name(multicast. sea. datagram. Multicast. Receiver Inet. Address multicast. Group = Inet. Address. get. By. Name(multicast. Group. Addr); Multicast. Socket socket = new Multicast. Socket(9876); socket. join. Group(multicast. Group); byte[] data = new byte[1000]; Datagram. Packet packet = new Datagram. Packet(data, data. length); socket. receive(packet); String message = new String( packet. get. Data(), 0, packet. get. Length()); socket. leave. Group(multicast. Group);

Useful sources of information • The Internet Engineering Task Force (IETF) which is at 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. au/LDP/HOWTO/. . . Multicast-HOWTO. html

Homework • Read through the code samples to convince yourself you understand what’s going 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 Comments, Suggestions. . . • How was the presentation paced? • Was there enough (or too much) technical content? • Any areas of particular interest? • Comments regarding presentation style?