Presentation is loading. Please wait.

Presentation is loading. Please wait.

EE2E1. JAVA Programming Lecture 9 Network Programming.

Similar presentations


Presentation on theme: "EE2E1. JAVA Programming Lecture 9 Network Programming."— Presentation transcript:

1 EE2E1. JAVA Programming Lecture 9 Network Programming

2 Contents Introduction to networks Introduction to networks TCP/IP Sockets TCP/IP Sockets A simple client program A simple client program A simple server program A simple server program A server with multiple clients A server with multiple clients Example – a simple email program Example – a simple email program URL connections URL connections Advanced networking technologies in Java Advanced networking technologies in Java

3 Introduction to Networks Network programming is surprisingly easy in Java Network programming is surprisingly easy in Java  Most of the classes relevant to network programming are in the java.net package Sending data out onto a network involves attaching a stream to a network connection (socket) and using the stream I/O functions we looked at in a previous lecture Sending data out onto a network involves attaching a stream to a network connection (socket) and using the stream I/O functions we looked at in a previous lecture The main issues to consider are client/server architectures and attaching multiple clients to a server The main issues to consider are client/server architectures and attaching multiple clients to a server First we will look an introduction to networking and the TCP/IP protocol First we will look an introduction to networking and the TCP/IP protocol

4 Internet Protocol (IP) Data is transmitted between computers in packets Data is transmitted between computers in packets  Each packet is marked with a destination address 130.65.83.2530data Internet Client Server Server Ports 14 30 80 Network packet

5 Each 4 byte address is the IP address Each 4 byte address is the IP address  Normally we refer to computers with domain names  www.bham.ac.uk  java.sun.com  The translation from domain name to IP address is carried out using DNS (Domain Name Service) IP has no provision for re-transmission in case of failure to deliver packets IP has no provision for re-transmission in case of failure to deliver packets  This is the job of the Transmission Control Protocol (TCP)  Most internet programs (eg the WWW, email etc) are based on TCP/IP

6 TCP/IP Sockets A TCP/IP socket enables a java program running on a client machine to open a connection with a web server A TCP/IP socket enables a java program running on a client machine to open a connection with a web server  There is a socket on both the client and server sides  Client server communication is carried out through input and output streams

7 Client socket Server socket Client output stream Server input stream Client input stream Server output stream

8 A simple client program Java has a Socket object which is an abstraction for a TCP/IP network endpoint to a client computer Java has a Socket object which is an abstraction for a TCP/IP network endpoint to a client computer  Connects to a server specified by the hostname “java.sun.com” and creates I/O streams int HTTP_PORT=80; Socket s= new Socket(“java.sun.com”,HTTP_PORT); InputStream instream=s.getInputStream(); OutputStream outstream=s.getOutputStream();

9 We can also directly specify the IP address instead of a string We can also directly specify the IP address instead of a string  Java has a InetAddress class to specify IP addresses  The (static) method getByName() converts from a hostname to an InetAddress int HTTP_PORT=80; InetAddress address=InetAddress(“java.sun.com”); Socket s= new Socket(address,HTTP_PORT);

10 Note that Java also provides a mechanism for the user datagram protocol (UDP) which is a simpler transport protocol that TCP Note that Java also provides a mechanism for the user datagram protocol (UDP) which is a simpler transport protocol that TCP  The Datagram socket is the abstraction to a UDP socket The difference between TCP and UDP is like the difference between a telephone conversation (albeit sent in packets) and sending a letter The difference between TCP and UDP is like the difference between a telephone conversation (albeit sent in packets) and sending a letter

11 As it stands, attempting to read from a socket will block until data becomes available As it stands, attempting to read from a socket will block until data becomes available  Its possible to set a timeout (in ms) after which a socket read will throw an exception int HTTP_PORT=80; Socket s= new Socket(“java.sun.com”,HTTP_PORT); s.setSoTimeOut(5000); // 5 seconds InputStream instream=s.getInputStream(); try{ // read socket} catch(InterruptedIOException e) { // process exception}

12 The above code assumes we have already created a Socket object from which to call setSoTimeOut() The above code assumes we have already created a Socket object from which to call setSoTimeOut()  But the Socket constructor can itself block if it can’t make a connection  This is possible if the server is unavailable  Needs a multi-threaded solution

13 class SocketOpener implements Runnable { public void SocketOpener(String aHost, int aPort, int aTimeOut) {} public Socket openSocket() { Thread t=new Thread(this); t.start();// Calls the run method try { t.join(timeOut); // Returns when thread dies or timeout expires } catch (interruptedException e) {} return socket; } public void run() {// Opens a socket try{socket=new Socket(host,port);} catch (IOException e) {} } private int timeOut; private String host; private int port; private Socket socket; };

14 We can now implement a simple client program which opens a socket to communicate with a web server We can now implement a simple client program which opens a socket to communicate with a web server  The hostname is supplied from the command line  A GET command is sent to the web server  This is a HTTP command to return the requested item  For example “GET / HTTP/1.0” means get the root page (/) from the host  The server will then return the requested information which is just HTML text

15 public class WebGet { public static void main(String[] args) { // Read command line args String host; String resource; if (args.length==2) { host=args[0]; resource=args[1]; System.out.println("Getting " + resource + " from " + host); } else { System.out.println("Getting / from java.sun.com"); host="java.sun.com"; resource="/"; }

16 try { // Open socket final int HTTP_PORT=80; SocketOpener so=new SocketOpener(host, HTTP_PORT, 10000); Socket s=so.openSocket(); // Get streams if (s!=null) { InputStream instream=s.getInputStream(); OutputStream outstream=s.getOutputStream(); // Turn streams in scanners and writers Scanner in=new Scanner(instream); PrintWriter out=new PrintWriter(outstream); // Send command String command="GET " + resource + " HTTP/1.0\n\n"; out.print(command); out.flush();

17 // Read response from the server while (in.hasNextLine()) { String input=in.nextLine(); System.out.println(input); } // Close socket s.close(); } else System.out.println("Error - couldn't open socket"); } catch(IOException e) {} }

18

19 A simple server program A server is a program which waits for a client to connect to it at a specified port A server is a program which waits for a client to connect to it at a specified port Normally a server would specify some application level protocol (such as HTTP) enabling clients to interact with the server Normally a server would specify some application level protocol (such as HTTP) enabling clients to interact with the server To start with, we will look at a simple server which simply echo’s the text sent to it by the client To start with, we will look at a simple server which simply echo’s the text sent to it by the client  We will use telnet as the client to test out our server

20 A ServerSocket object is created to establish a server connection A ServerSocket object is created to establish a server connection  The accept() method then waits for a client to connect  accept() waits indefinitely and returns a Socket object that represents the connection to the client int portNumber=8250; ServerSocket s=new ServerSocket(portNumber); Socket clientSoc=s.accept();

21 public class EchoServer { public static void main(String[] args) { try { ServerSocket s=new ServerSocket(8250); Socket clientSoc=s.accept(); BufferedReader in=new BufferedReader(new InputStreamReader(clientSoc.getInputStream())); PrintWriter out=new PrintWriter(clientSoc.getOutputStream(),true); out.println("Hello client! Enter BYE to exit");

22 boolean done=false; while (!done) { String line=in.readLine(); if (line==null) done=true; else { out.println("Echo: " + line); if (line.trim().equals("BYE")) done=true; } clientSoc.close(); } catch(Exception e){} }

23 We can run the telnet client on the local host (IP 127.0.0.1) at port 8250 We can run the telnet client on the local host (IP 127.0.0.1) at port 8250  Use telnet command open 127.0.0.1 8250

24 A server with multiple clients In the real world a server will want to link to many clients In the real world a server will want to link to many clients  Examples include servers providing information (such as weather or travel info) or online ticket booking  Clearly we don’t want a single client program to ‘hog’ a server and prevent other clients from accessing it  By implementing a multi-threaded server, we can allow multiple connections  We simply need to create a new thread to handle each newly accepted client connection

25 int portNumber=8250; ServerSocket s=new ServerSocket(portNumber); while(true) // accept multiple clients { Socket clientSoc=s.accept(); Thread t=new ThreadedEchoHandler(clientSoc); t.start();// Handle the client communication }

26 We can implement 2 classes, MultiThreadedEchoServer and ThreadedEchoHandler to handle multiple client connections We can implement 2 classes, MultiThreadedEchoServer and ThreadedEchoHandler to handle multiple client connections  MultiThreadedEchoServer creates ThreadedEchoHandler objects for each client  ThreadedEchoHandler extends Thread and its run() method handles client I/O  Its implementation is the same as the main method of the EchoServer class

27 MultiThreadedEchoServer object Telnet ThreadedEchoHandler object

28 public class MultiThreadedEchoServer { public static void main(String[] args) { int clientID=1; try { ServerSocket s=new ServerSocket(8250); for (;;) { Socket clientSoc=s.accept(); System.out.println("New client connection” + clientID); new ThreadedEchoHandler(clientSoc,clientID).start(); clientID++; } catch(Exception e){} }

29 An email program As a simple example of socket programming we can implement a program that sends email to a remote site As a simple example of socket programming we can implement a program that sends email to a remote site  This is taken from Core Java, vol 2, chapter 3 Email servers use port number 25 which is the SMTP port Email servers use port number 25 which is the SMTP port  Simple mail transport protocol

30 A client socket to the mail server can be opened on port 25 A client socket to the mail server can be opened on port 25 SMPT uses the following protocol SMPT uses the following protocol Socket s=new Socket(“engmail.bham.ac.uk”,25); HELO sending host MAIL FROM:sender email address RCPT TO: recipient email address DATA mail message …. QUIT

31 The email program uses a simple GUI to input the required information The email program uses a simple GUI to input the required information The send button on the GUI calls the sendMail() method which outputs the correct protocol to the mail server The send button on the GUI calls the sendMail() method which outputs the correct protocol to the mail server Socket s=new Socket(“engmail.bham.ac.uk”,25); out=new PrintWriter(s.getOutputStream()); String hostname=InetAddress.getLocalHost().getHostName(); out.println(“HELO “ + hostname); out.println(“MAIL FROM: “ + from.getText()); etc

32

33

34 URL connections We have seen that to send or retrieve information to a web server, we use the HTTP protocol through a client socket attached to port 80 We have seen that to send or retrieve information to a web server, we use the HTTP protocol through a client socket attached to port 80 We can do this by using normal socket-based programming and sending the correct HTTP commands We can do this by using normal socket-based programming and sending the correct HTTP commands However, Java has specific support for the HTTP protocol through its URLConnection class However, Java has specific support for the HTTP protocol through its URLConnection class  Its very easy to retrieve a file from a web server by simply providing the file’s url as a string

35 This sets up an input stream from a url connection This sets up an input stream from a url connection  Can turn this into a Scanner object for text processing The URLConnection class also has additional functionality related to the HTTP protocol The URLConnection class also has additional functionality related to the HTTP protocol  Querying the server for header information  Setting request properties URL u=new URL(“http://www.bham.ac.uk”);http://www.bham.ac.uk URLConnection c=u.openConnection(); InputStream in=c.getInputStream();

36 The following simple example program opens a web page and displays the HTML The following simple example program opens a web page and displays the HTML It also checks the server response code It also checks the server response code  404 if the page is not found  200 if the connection succeeded Uses a Scanner object to output the lines of HTML Uses a Scanner object to output the lines of HTML

37 public class URLGet { public static void main(String[] args) throws IOException { String urlName; if (args.length > 0) urlName = args[0]; else urlName = "http://java.sun.com"; URL url = new URL(urlName); URLConnection c = url.openConnection(); // Check response code HttpURLConnection httpConnection = (HttpURLConnection) c; int code =httpConnection.getResponseCode(); String message=httpConnection.getResponseMessage(); System.out.println(code + " " + message); if (code!=HttpURLConnection.HTTP_OK) return; // Read server response InputStream instream=connection.getInputStream(); Scanner in=new Scanner(instream); while (in.hasNextLine()) { String input=in.nextLine(); System.out.println(input); }

38

39 Advanced networking technologies in Java In this section we will look briefly at more advanced technologies for networking in Java without looking in detail at code In this section we will look briefly at more advanced technologies for networking in Java without looking in detail at code  Sending data to a web server  CGI and servlet technology  Inter-object communication  Remote method invocation (RMI)  CORBA

40 CGI and servlet technology We often need to send data back to a web server We often need to send data back to a web server  Typically we fill out an online form displayed on a web browser and click a ‘submit’ button  Older web technology uses a CGI script to process the information  CGI stands for Common Gateway Interface  Typically it is a program running on the server and written in a scripting language like Perl  The CGI script processes the data submitted and sends back a response to the client – usually a HTML page

41 Server CGI script Client web browser http server Form data Server starts CGI script Client displays web form Script produces reply page Reply page submit Server returns reply

42 CGI is well established and still widely used technology CGI is well established and still widely used technology Its major disadvantage is that each request forks a new process which can make it slow Its major disadvantage is that each request forks a new process which can make it slow  Makes sharing resources tricky Also there are some security flaws with CGI – it can be fooled into running commands on the server since it uses an interpreted scripted language Also there are some security flaws with CGI – it can be fooled into running commands on the server since it uses an interpreted scripted language

43 Servlets are Java classes which extend the HttpServlet class. They run inside a Servlet Container which calls methods of the servlet Servlets are Java classes which extend the HttpServlet class. They run inside a Servlet Container which calls methods of the servlet  The servlet container must be part of a compliant web server which contains the Java runtime environment  They run in the Java virtual machine inside the web server and so are portable and secure  Unlike CGI each separate request creates a new thread which is able to share resources with existing running threads

44 Inter-object communication Object orientation is all about objects ‘communicating’ with each other by calling each others’ methods Object orientation is all about objects ‘communicating’ with each other by calling each others’ methods  What if the objects are distributed across a network?  What if the objects are implemented in different languages? (eg Java and C++)

45 There are two mechanisms for inter object communication across a network There are two mechanisms for inter object communication across a network  Language independent mechanism is called CORBA  Common object request broker  A separate language neutral broker object handles all messages between the objects  Generally rather slow and complex because of its generality and ability to handle legacy code  If both objects are implemented in Java a much simpler mechanism is Remote Method Invocation (RMI)

46 In RMI, a client object calls a method of a server object on a different machine In RMI, a client object calls a method of a server object on a different machine  Client/server terminology only applies to the single method call Client object Server object Method call with parameters Returned data (objects)

47 All this seems easy but the actual behind the scenes issues are complex All this seems easy but the actual behind the scenes issues are complex  Actual inter-object communictation is done through separate stub objects which package remote method calls and parameters  The server registers its objects with a naming service  The clients finds the remote objects using a url : “rmi://servername.com/”  There are complex security issues involved also as calling a remote method locally can introduce viruses However, much of this is transparent to the programmer and RMI is relatively straighforward However, much of this is transparent to the programmer and RMI is relatively straighforward

48 And finally….. Network programming is a doddle in Java Network programming is a doddle in Java Sockets look like ordinary I/O streams from an application programming viewpoint Sockets look like ordinary I/O streams from an application programming viewpoint The main issues are writing multi-threaded code for multiple client applications The main issues are writing multi-threaded code for multiple client applications  In the last lab exercise, you will have the opportunity to write a multi-threading server for a network-based game!

49 A very early …….. Merry Christmas!!


Download ppt "EE2E1. JAVA Programming Lecture 9 Network Programming."

Similar presentations


Ads by Google