A Java Networking

52
Advanced Java Programming Unit One: Networking Gareth Lee Department of Electrical and Electronic Engineering, University of Western Australia John Morris Gareth Lee

description

Java networking

Transcript of A Java Networking

  • Advanced Java Programming Unit One: Networking Gareth LeeDepartment of Electrical and Electronic Engineering,University of Western AustraliaJohnMorrisGareth Lee

  • OverviewJavas network supportAddressing other machinesCommunicating using TCP/IPCommunicating using UDPBroadcasting and multicasting

  • Recommended ReadingJava Network Programming, Elliotte Rusty Harold, OReilly and Associates, 1997, ISBN 1-56592-227-1TCP/IP Network Administration, Second Edition, Craig Hunt, OReilly and Associates, 1997, ISBN 1-56592-322-7The Java Developers connection: http://www.javasoft.com/jdcThe Javadoc documentation

  • Network ProgrammingMechanisms by which software running on two or more computational devices can exchange messagesDesktop ComputersPDAs / Set Top Boxes / Mobile Telephones?Java is a network centric programming languageJava abstracts details of network implementation behind a standard APIPortable (and future proof) . . .but may be rather limiting

  • A programming model for network communicationsDealt with in this Unit One.Dealt with in this Unit Two.

  • 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 machineEasy to write programsEasy to build network hardwareWorks 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 portsPorts 20/21File Transfer ProtocolPort 23TelnetPort 25Simple Mail Transport Proto.Port 79FingerPort 80HTTPPort 110POP3 (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 dont use addresses very efficiently and were running out fast (UWA doesnt need 65536 separate addresses)

  • Next Generation InternetThe solution is IPv6 which uses 128 bit addressesImproves services such as multicasting and secure communicationSeveral addresses per m2 of the Earths surface (3.4 x 1038 to be precise)Not yet widely deployed by ISPsPerhaps widely deployed in 2-4 yearsWell written Java software should move to IPv6 without modification/recompilationOne benefit of abstracted APIs

  • IP Addresses and JavaJava has a class java.net.InetAddress which abstracts network addressesServes three main purposes:Encapsulates an addressPerforms 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 addressCurrently uses IPv4 (a 32 bit address)Will support other address formats in futureAllows an address to be obtained from a host name and vice versaIs 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 methodInetAddress getByName(String hostName)hostName can be host.domain.com.au, orhostName can be 130.95.72.134InetAddress 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 objectsimport 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 ProtocolTCP is built on top of IPProvides 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 successionContains an error recovery mechanism to recover datagrams which are lostThese features make application development simpler and so it is widely used

  • Transmission Control ProtocolUsed by FTP / Telnet / Finger and numerous other network applicationsUsed 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 Socketjava.net.ServerSocket is used by servers so that they can accept incoming TCP/IP connectionsA server is a piece of software which advertises and then provides some service on requestjava.net.Socket is used by clients who wish to establish a connection to a (remote) serverA 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 connectionsCreates a dynamically allocated port for each newly established connectionProvides a Socket connected to the new portMaintains 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 themSome useful methods:Socket accept()Blocks waiting for a client to attempt to establish a connectionvoid close()Called by the server when it is shutting down to ensure that any resources are deallocatedMore details in the Javadoc (as always!)

  • java.net.Socket (1)Provides access to TCP/IP streamsBi-directional communication between sender and receiverCan 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 streamsInput stream allows reception of data from the other partyInputSteam getInputStream()Output stream allows dispatch of data to the other partyOutputStream getOutputStream()

  • How it all fits togetherClient (sid)Server (fred)ServerSocket ss.s = ss.accept()s = new Socket(fred, 80)Socket ss.getInputStream()s.getOuputStream()s.getInputStream()s.getOuputStream()

  • A sample TCP serverpublic 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 (UnknownHostException uhe) { // Very unlikely to occur } catch (IOException ioe) { // May occur if the client misbehaves? } }

  • A sample TCP clientpublic 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 dataEach is like a parcel that can be addressed and sent to an recipient anywhere on the InternetThis 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 chunksPoor for (lossless) stream based communicationsMakes 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 datagramsUDP can be used for economical point-to-point communications over LANsUnix 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 receivedHas the following attributes:Destination/source addressDestination/source port numberData bytes constituting the messageLength 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 hostUsed to send or receive datagramsNote: 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 networkvoid receive(DatagramPacket emptyPacket)Waits until a datagram and fills in emptyPacket with the message. . . and a few more in the Javadoc

  • sea.datagram.DatagramSenderThis example sends datagrams to a specific host (anywhere on the Internet)The steps are as follows:Create a new DatagramPacketPut some data which constitutes your message in the new DatagramPacketSet a destination address and port so that the network knows where to deliver the datagramCreate 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.DatagramSenderbyte[] data = This is the message.getBytes();DatagramPacket packet = new DatagramPacket(data, data.length);

    // Create an addressInetAddress destAddress = InetAddress.getByName(fred.domain.com);packet.setAddress(destAddress);packet.setPort(9876);

    DatagramSocket socket = new DatagramSocket();socket.send(packet);

  • sea.datagram.DatagramReceiverThe 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 arrivalsUse 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 spacebyte[] data = new byte[1500];DatagramPacket packet = new DatagramPacket(data, data.length);

    DatagramSocket socket = new DatagramSocket(9876);

    // This call will block until a datagram arrivessocket.receive(packet);

    // Convert the bytes back into a String and printString message = new String(packet.getData(), 0, packet.getLength());System.out.println("message is " + message);System.out.println("from " + packet.getAddress());

  • But its never quite that simple!Several of the constructors/methods throw exceptions which I have omittedEach 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

  • BroadcastingBroadcasting allows a single datagram to be sent to a group of listenersThe group consists of all the computers within the local networkThe previous code examples can be used for broadcastingJust change the address: each network has a unique broadcast address

  • IP addresses revisitedEach 32 bit IP number consists of two components:The network addressThe unique international address of the networkThe host address The unique address of a specific host in the netThere are three classes of network address denoted class A, B and C

  • Class A,B and C addresses192. 85 . 35 . 87Network Address ByteHost Address Byte0...10...110...

  • Broadcast addressesCIIPS has a class C network which has the address 130.95.72This portable computer has host address 134 within the CIIPS networkEach 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.255Broadcasts 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 networkRouters 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 addressMulticast 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 groupThis 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 groups224.0.0.1All hosts within local subnet224.0.1.7Audio news multicast224.0.1.12Video from IETF meetings224.0.1.20Expts. within local subnet224.0.1.25NBC Professional NewsThere are 268 million multicast addresses (in IPv4) with 65 thousand ports in each!

  • java.net.MulticastSocketSubclass of java.net.DatagramSocketConstructed the same wayAdds some extra methods:void joinGroup(InetAddress mcastGroup)Enter the specifies group so that you can send or receive datagramsvoid leaveGroup(InetAddress mcastGroup)Leave a group that you previously joinedvoid setTimeToLive(int ttl)Sets how far your datagrams will travel before routers ignore themint getTimeToLive()

  • sea.datagram.MulticastSenderSending similar to the previous example. .. . .but must register with the multicast group and decide the longevityThe 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.MulticastSenderInetAddress 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.MulticastReceiverThe 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.MulticastReceiverInetAddress 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 informationThe Internet Engineering Task Force (IETF) which is at http://www.ietf.org -- you will be able to download RFCs from hereMulticasting try reading the HOWTO which is available from the URL: http://ftp.southcom.com.au/LDP/HOWTO/...Multicast-HOWTO.html

  • HomeworkRead through the code samples to convince yourself you understand whats going onSample code can be downloaded from http://ciips.ee.uwa.edu.au/~garethIf 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?