Network Programming

Benoît Garbinato

1

Network programming
Network programming is not distributed programming (somewhat lower-level) They both rely on:
computers as processing & storage resources a network and a common protocol stack

But network programming lacks:

naming and location transparency an integrated programming & operating model (usually achieved thanks to a middleware)

Network Programming © Benoît Garbinato

2

g.1 header actual data Data encapsulation: Network Programming © Benoît Garbinato viewed by layer i as data viewed by layer i+1 as data 4 . routing of data packets (no flow control). end-to-end connection. basic application-level functionality (http.The OSI model (1) application application presentation session transport network data link network data link physical link Network Programming © Benoît Garbinato application application presentation logical peer-to-peer link session transport network data link 3 The OSI model (2) Physical link Data link Network Transport Session Presentation Application physical medium. ftp. failure detection & reconnection in case of crashes. marshaling convention). electrical/optical signal processing. order. standard data representation (e. grouping of bits into blocks. local address format. medium access layer. etc. smtp.. error detection/correction.). global address format. retransmission. layer i + 1 header layer i header layer i . flow control.

The Internet: some history In the middle of the cold war. spreads into the academic community (also very distributed). the ARPAnet technology. A key design issue of ARPAnet was to resist to the massive destruction resulting from a nuclear attack. the Department of Defense (DOD) decides to build a set of tools for interconnecting computer networks. which had developed it. early 1970s. also named TCP/IP (after its two main building blocks). The responsibility of this task falls on the Advance Research Project Agency (ARPA). Network Programming © Benoît Garbinato 5 TCP/IP TCP " Transmission Control Protocol IP " Internet Protocol It Is cornerstone of the Internet It is de facto standard It is an often misunderstood technology It is an old yet alive protocol suite Network Programming © Benoît Garbinato 6 . which develops the ARPAnet protocol suite. ! Fully distributed architecture (no single point of failure) In the 1980s.

2 = - Network Programming © Benoît Garbinato 8 .g.171. An IP address consists of 32-bits (4 bytes) and is usually written in dotted decimal format. 130. e.8 Class A B C D E First 1-126 27 14 Networks = 126 224 .223..2 16 Hosts 16’777’21 net id 65’534 254 - Address format host id host id host id net id net id multicast reserved 128-191 2 192-223 221 224-239 240-247 = 16’384 2 -2 = 2’097’152 28 .The OSI model & TCP/IP Internet Protocol (IP)! #! Packet oriented Routing with best-effort guarantee Error detection Datagram fragmentation Transmission Control Protocol (TCP)! # Stream oriented Reliability guarantee FIFO order guarantee Network Layer (OSI no 3) Transport Layer (OSI no 4) Network Programming © Benoît Garbinato 7 Naming hosts with TCP/IP An IP address is used by the IP protocol (Network Layer) to name hosts (computers) and routers.

operating system port TCP or UDP IP hardware network port port IP address port num ber IP address port num ber IP address port num ber Network Programming © Benoît Garbinato 10 .76 % 106 km ! 1m 26 2. applications are named (addressed) using ports. At the operating system level.25 km ? km % 10 10 % distance earth-moon 1m 10 km ! 1018 % distance earth-sun Network Programming © Benoît Garbinato 9 Naming applications Within a single host.Towards IPv6 Addresses encoded on 128 bits ! 2128 $ 3.4 % 1038 addresses are available 3. this is known as port multiplexing.

TCP versus UDP (1) TCP " Transmission Control Protocol stream UDP " User Datagram Protocol datagrams Network Programming © Benoît Garbinato 11 TCP versus UDP (2) TCP and UDP exhibit dual features: connection oriented reliable channels YES NO fifo ordering YES NO message boundaries NO YES TCP UDP YES NO Network Programming © Benoît Garbinato 12 .

.net package Network Programming © Benoît Garbinato 13 TCP Sockets Because TCP is connection-oriented....The Socket abstraction Sockets are programming abstractions that represent bidirectional communication endpoints between two or more processes There exists two types of sockets : TCP sockets and UDP sockets In Java...} public InputStream getInputStream() {..... } This captures the asymmetry when establishing a communication channel Network Programming © Benoît Garbinato 14 .} .} .. sockets are instances of various classes found in the java..} public void close() {.. public ServerSocket(int port) {. int port) {. we have two classes for TCP sockets in Java: Client public class Socket { .. } Server public class ServerSocket { ...} public Socket accept() {... public Socket(String host.} public OutputStream getOutputStream() {...

in = new BufferedReader(new InputStreamReader(mySession. System. mySession.println("-> " + fromServer).readLine().exit(1). System. BufferedReader in= null. out.out. String fromServer. out = new PrintWriter(mySession.length < 1) { System.close(). mot.println("Hostname missing. } catch (UnknownHostException e) { System.err. clientSession.close(). String word. } out. "réparti").getInputStream())).").out. if (mot == null) mot= "sorry.out.get(word).out.close(). ask the dictionary server!").TCP sockets: server side public class DictionaryServer { private static Dictionary dico= new Hashtable(). no translation available for \"" + word + "\" !". } } } Network Programming © Benoît Garbinato 16 . // Etc. } mySession = new Socket(args[0]. BufferedReader in= null. connectionServer. stdIn.close().close().println(mot). true). } out.getInputStream())). } catch (IOException e) { System.exit(1). fromUser. dico. stdIn = new BufferedReader(new InputStreamReader(System.readLine()) != null ) { mot= (String) dico. PrintWriter out= null. clientSession = connectionServer. fromServer= in.exit(1). in. System.in)).println("Host Unknown: " + args[0]). System.put("inheritance". PrintWriter out= null.err.getOutputStream().close(). try { if (args. true). in.accept(). while ( (word = in.close().println("No connection to: " + args[0]).equals("quit") ) { out. 4444).put("distributed".exit(1). dico.. "héritage").println(fromUser). BufferedReader stdIn= null. System. } } } Network Programming © Benoît Garbinato 15 TCP sockets: client side public class DictionaryClient { public static void main(String[] args) { Socket mySession= null. Socket clientSession= null..println("Go on.readLine()). while ( !(fromUser = stdIn. out = new PrintWriter(clientSession. in = new BufferedReader(new InputStreamReader(clientSession. System. try { connectionServer = new ServerSocket(4444). public static void main(String[] args) { ServerSocket connectionServer= null.getOutputStream(). } catch (IOException e) { System.close().println(e).

BufferedReader in= new BufferedReader(new InputStreamReader(clientSession. streams are instances of various classes found in the java. sockets.. byte arrays in memory.. Socket clientSession= connectionServer.Streams in Java (1) Streams offer a unified programming abstraction for reading and writing data Streams can encapsulate various types of data sources...in & System. etc. data source byte stream character stream buffered character stream Printer and writer classes are special streams manipulating only characters Standard operating systems-level input and output streams are also accessed via Java streams (System. Streams can encapsulate other streams to stack up processing of the data In Java.g. e. files.out) Network Programming © Benoît Garbinato 18 ..getInputStream())).io package Network Programming © Benoît Garbinato 17 Streams in Java (2) . .accept().

Collection yourCollection = (Collection) in. ObjectInputStream in= new ObjectInputStream(clientSession.getInputStream()).Serializable interface.writeObject(myCollection).readObject().getOutputStream()). an object becomes serializable Two special stream classes allow for writing and reading objects : ObjectOutputStream out = new ObjectOutputStream(clientSession. only about bytes Problem:!how can we send a complete object graph across the network? Solution:! almost any Java object can be automatically transformed into a sequence of bytes and recreated from that sequence 1101000110101100111010011101001110001110100011110 Network Programming © Benoît Garbinato 19 Objects through the wire (2) The process of transforming an object graph into a byte sequence is known as serialization or marshaling By implementing the java. out.Objects through the wire (1) Fact:! the network knows nothing about objects. Network Programming © Benoît Garbinato 20 .io.

..} // Let the system choose a port public DatagramSocket(int port) {. just like everyone else.} public InetAddress getAddress() {.close(). socket = new DatagramSocket(4445).getPort()..length). if (quote == null) { moreQuotes= false....} public void close() {.. Lottery: A tax on people who are bad at math.. the DatagramPacket is also a key class when working with UDP sockets 21 Network Programming © Benoît Garbinato UDP sockets: server side public class QuoteServer { public static void main(String[] args) throws Exception { DatagramSocket socket = null. } However.UDP Sockets Because UDP is connectionless.. boolean moreQuotes= true.getBytes().. why doesn't this magnet pick up this floppy disk? Give me ambiguity or give me something else. wet and hungry. } socket. String quote = null.. Hard work has a future payoff.} public void send(DatagramPacket packet) {. I'm stuffed!" A flashlight is a case for holding dead batteries. Error. Laziness pays off now. packet = new DatagramPacket(buf.press F1 to continue.. address.S. He who laughs last thinks slowest! Always remember you're unique.readLine(). buf.getAddress(). buf. Daddy.length. we have only one class for UDP sockets in Java: public class DatagramSocket { .) {.. port).. quote = in. Artificial Intelligence usually beats real stupidity. in = new BufferedReader(new FileReader("one-liners.} public byte[] getData() {.. Without it we'd all be dead...receive(packet). .: We've got what it takes to take what you've got! We are born naked. DatagramPacket packet = new DatagramPacket(buf. Scotty.. } } Network Programming © Benoît Garbinato 22 . } InetAddress address = packet.. no keyboard .} else { buf = quote.. public DatagramSocket() {." Puritanism: The haunting fear that someone... } public class DatagramPacket { .. Make it idiot proof and someone will make a better idiot.R. while (moreQuotes) { byte[] buf. BufferedReader in = null. somewhere may be happy.} . socket..txt")).} ... Life is wonderful.} public void receive(DatagramPacket packet) {. Trigger?" "No thanks. int port = packet. public DatagramPacket(. Now beam down my clothes. Then things get worse.getBytes(). "More hay. Roy. I. "Very funny. bye!"). socket.send(packet)... buf= ("No more. There's too much blood in my caffeine system.

address.out.readLine(). InetAddress address = InetAddress.length.UDP sockets: client side public class QuoteClient { public static void main(String[] args) throws Exception { if (args. buf. buf.receive(packet). DatagramPacket packet = new DatagramPacket(buf. packet = new DatagramPacket(buf.255. socket. socket.0.close(). System.length != 1) { System.in)).println("Go on.getData()).println("-> " + received).out.length). System. ask for a quote by typing return!"). String received = new String(packet.0 and 239. while ( !stdIn. } } Network Programming © Benoît Garbinato 23 UDP Multicast A multicast allows for one-to-many communication in an anonymous way A multicast address is an address between 224.equals("quit") ) { byte[] buf = new byte[256].getByName(args[0]). BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.255.exit(1).out.0. multicast is available thanks to a the MulticastSocket class: Methods joinGroup() and leaveGroup() allow a receiver to respectively join and leave a multicast group Method setTimeToLive() allows a sender to restrict the number of hubs its sent messages are going through Network Programming © Benoît Garbinato 24 .println("Missing hostname"). and defines a so-called multicast group In Java.255. } DatagramSocket socket = new DatagramSocket(). 4445). System.send(packet). } socket.

readLine(). quote = in.out.getBytes(). } InetAddress group = InetAddress.0.1"). 4446).indexOf("bye") != -1 ) break.length). buf= ("No more.print("Waiting for the next quote: "). String received = new String(packet.} else { buf = quote.receive(packet).getByName("230. DatagramPacket packet = new DatagramPacket(buf.0. byte[] buf = new byte[256].printStackTrace().leaveGroup(group). } } Network Programming © Benoît Garbinato 25 UDP Multicast: receiver public class MulticastQuoteReceiver { public static void main(String[] args) throws Exception { try { MulticastSocket socket = new MulticastSocket(4446). } catch (Exception e) { e.getByName("230.1"). DatagramPacket packet = new DatagramPacket(buf. System.currentThread(). boolean moreQuotes= true. } } } Network Programming © Benoît Garbinato 26 . } socket.joinGroup(group).txt")).getBytes(). socket = new MulticastSocket().close(). socket. BufferedReader in = null. if ( received.out.0. while (moreQuotes) { Thread. buf. while (true) { byte[] buf = new byte[256].UDP Multicast: sender public class MulticastQuoteSender { public static void main(String[] args) throws Exception { MulticastSocket socket = null. if (quote == null) { moreQuotes= false. group. bye!"). socket.send(packet). socket.println(received). socket. } socket.length. socket.sleep(500). InetAddress group = InetAddress.0. in = new BufferedReader(new FileReader("one-liners. System. String quote = null.setTimeToLive(0). buf.getData()).close().

Sign up to vote on this title
UsefulNot useful