ee2e1. java programming lecture 9 network programming

49
EE2E1. JAVA Programming Lecture 9 Lecture 9 Network Programming Network Programming

Upload: ursula-lyons

Post on 25-Dec-2015

248 views

Category:

Documents


11 download

TRANSCRIPT

Page 1: EE2E1. JAVA Programming Lecture 9 Network Programming

EE2E1. JAVA Programming

Lecture 9Lecture 9

Network ProgrammingNetwork Programming

Page 2: EE2E1. JAVA Programming Lecture 9 Network Programming

Contents Introduction to networksIntroduction to networks TCP/IP SocketsTCP/IP Sockets A simple client programA simple client program A simple server programA simple server program A server with multiple clientsA server with multiple clients Example – a simple email programExample – a simple email program URL connectionsURL connections Advanced networking technologies in JavaAdvanced networking technologies in Java

Page 3: EE2E1. JAVA Programming Lecture 9 Network Programming

Introduction to Networks Network programming is surprisingly easy in JavaNetwork programming is surprisingly easy in Java

Most of the classes relevant to network programming Most of the classes relevant to network programming are in the java.net package are in the java.net package

Sending data out onto a network involves attaching a Sending data out onto a network involves attaching a stream to a network connection (socket) and using the stream to a network connection (socket) and using the stream I/O functions we looked at in a previous lecturestream I/O functions we looked at in a previous lecture

The main issues to consider are client/server architectures The main issues to consider are client/server architectures and attaching multiple clients to a serverand attaching multiple clients to a server

First we will look an introduction to networking and the First we will look an introduction to networking and the TCP/IP protocolTCP/IP protocol

Page 4: EE2E1. JAVA Programming Lecture 9 Network Programming

Internet Protocol (IP) Data is transmitted between computers in Data is transmitted between computers in packetspackets

Each packet is marked with a destination address Each packet is marked with a destination address

130.65.83.25 30 data

Internet

ClientServer

Server Ports

14

30

80

Network packet

Page 5: EE2E1. JAVA Programming Lecture 9 Network Programming

Each 4 byte address is the IP addressEach 4 byte address is the IP address Normally we refer to computers with Normally we refer to computers with domain namesdomain names

www.bham.ac.ukwww.bham.ac.uk java.sun.comjava.sun.com

The translation from domain name to IP address is carried out using DNS (The translation from domain name to IP address is carried out using DNS (Domain Name Service)Domain Name Service) IP has no provision for re-transmission in case of failure to deliver packetsIP has no provision for re-transmission in case of failure to deliver packets

This is the job of the This is the job of the Transmission Control Protocol Transmission Control Protocol (TCP)(TCP) Most internet programs (eg the WWW, email etc) are based on TCP/IPMost internet programs (eg the WWW, email etc) are based on TCP/IP

Page 6: EE2E1. JAVA Programming Lecture 9 Network Programming

TCP/IP Sockets

A TCP/IP socket enables a java program A TCP/IP socket enables a java program running on a client machine to open a running on a client machine to open a connection with a web serverconnection with a web server There is a socket on both the client and There is a socket on both the client and

server sidesserver sides Client server communication is carried Client server communication is carried

out through input and output streamsout through input and output streams

Page 7: EE2E1. JAVA Programming Lecture 9 Network Programming

Client socket

Server socket

Client output stream

Server input stream

Client input stream

Server output stream

Page 8: EE2E1. JAVA Programming Lecture 9 Network Programming

A simple client program Java has a Java has a SocketSocket object which is an abstraction object which is an abstraction

for a TCP/IP network endpoint to a client for a TCP/IP network endpoint to a client computercomputer

Connects to a server specified by the hostname Connects to a server specified by the hostname “java.sun.com” and creates I/O streams“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();

Page 9: EE2E1. JAVA Programming Lecture 9 Network Programming

We can also directly specify the IP address We can also directly specify the IP address instead of a stringinstead of a string Java has a Java has a InetAddressInetAddress class to specify IP class to specify IP

addressesaddresses The (static) method The (static) method getByName()getByName()

converts from a hostname to an converts from a hostname to an InetAddressInetAddress

int HTTP_PORT=80;

InetAddress address=InetAddress(“java.sun.com”);

Socket s= new Socket(address,HTTP_PORT);

Page 10: EE2E1. JAVA Programming Lecture 9 Network Programming

Note that Java also provides a mechanism Note that Java also provides a mechanism for the user datagram protocol (UDP) which for the user datagram protocol (UDP) which is a simpler transport protocol that TCPis a simpler transport protocol that TCP The The DatagramDatagram socket is the abstraction to socket is the abstraction to

a UDP socketa UDP socket

The difference between TCP and UDP is The difference between TCP and UDP is like the difference between a telephone like the difference between a telephone conversation (albeit sent in packets) and conversation (albeit sent in packets) and sending a lettersending a letter

Page 11: EE2E1. JAVA Programming Lecture 9 Network Programming

As it stands, attempting to read from a As it stands, attempting to read from a socket will block until data becomes socket will block until data becomes availableavailable Its possible to set a timeout (in ms) after Its possible to set a timeout (in ms) after

which a socket read will throw an which a socket read will throw an exceptionexception

int HTTP_PORT=80;Socket s= new Socket(“java.sun.com”,HTTP_PORT);s.setSoTimeOut(5000); // 5 secondsInputStream instream=s.getInputStream();

try{ // read socket}catch(InterruptedIOException e) { // process exception}

Page 12: EE2E1. JAVA Programming Lecture 9 Network Programming

The above code assumes we have already The above code assumes we have already created a created a SocketSocket object from which to call object from which to call setSoTimeOut()setSoTimeOut() But the But the SocketSocket constructor can itself constructor can itself

block if it can’t make a connectionblock if it can’t make a connection This is possible if the server is This is possible if the server is

unavailableunavailable Needs a multi-threaded solutionNeeds a multi-threaded solution

Page 13: EE2E1. JAVA Programming Lecture 9 Network Programming

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 methodtry{

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;

};

Page 14: EE2E1. JAVA Programming Lecture 9 Network Programming

We can now implement a simple client program which We can now implement a simple client program which opens a socket to communicate with a web serveropens a socket to communicate with a web server The hostname is supplied from the command lineThe hostname is supplied from the command line A GET command is sent to the web serverA GET command is sent to the web server

This is a HTTP command to return the requested This is a HTTP command to return the requested itemitem

For example “GET / HTTP/1.0” means get the root For example “GET / HTTP/1.0” means get the root page (/) from the hostpage (/) from the host

The server will then return the requested The server will then return the requested information which is just HTML textinformation which is just HTML text

Page 15: EE2E1. JAVA Programming Lecture 9 Network Programming

public class WebGet{ public static void main(String[] args) {

// Read command line argsString 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="/";}

Page 16: EE2E1. JAVA Programming Lecture 9 Network Programming

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();

Page 17: EE2E1. JAVA Programming Lecture 9 Network Programming

// 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) {} }}

Page 18: EE2E1. JAVA Programming Lecture 9 Network Programming
Page 19: EE2E1. JAVA Programming Lecture 9 Network Programming

A simple server program A server is a program which waits for a A server is a program which waits for a

client to connect to it at a specified portclient to connect to it at a specified port Normally a server would specify some Normally a server would specify some

application level protocol (such as HTTP) application level protocol (such as HTTP) enabling clients to interact with the serverenabling clients to interact with the server

To start with, we will look at a simple server To start with, we will look at a simple server which simply echo’s the text sent to it by the which simply echo’s the text sent to it by the clientclient We will use telnet as the client to test out We will use telnet as the client to test out

our serverour server

Page 20: EE2E1. JAVA Programming Lecture 9 Network Programming

A A ServerSocketServerSocket object is created to establish a server connection object is created to establish a server connection

The The accept() accept() method then waits for a client to connect method then waits for a client to connect

accept() accept() waits indefinitely and returns a waits indefinitely and returns a Socket Socket objectobject that represents that represents the connection to the clientthe connection to the client

int portNumber=8250;

ServerSocket s=new ServerSocket(portNumber);

Socket clientSoc=s.accept();

Page 21: EE2E1. JAVA Programming Lecture 9 Network Programming

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");

Page 22: EE2E1. JAVA Programming Lecture 9 Network Programming

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){} }}

Page 23: EE2E1. JAVA Programming Lecture 9 Network Programming

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

open 127.0.0.1 8250

Page 24: EE2E1. JAVA Programming Lecture 9 Network Programming

A server with multiple clients In the real world a server will want to link to many clientsIn the real world a server will want to link to many clients

Examples include servers providing information (such as weather Examples include servers providing information (such as weather or travel info) or online ticket bookingor travel info) or online ticket booking

Clearly we don’t want a single client program to ‘hog’ a server Clearly we don’t want a single client program to ‘hog’ a server and prevent other clients from accessing itand prevent other clients from accessing it

By implementing a multi-threaded server, we can allow multiple By implementing a multi-threaded server, we can allow multiple connectionsconnections

We simply need to create a new thread to handle each newly We simply need to create a new thread to handle each newly accepted client connectionaccepted client connection

Page 25: EE2E1. JAVA Programming Lecture 9 Network Programming

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

}

Page 26: EE2E1. JAVA Programming Lecture 9 Network Programming

We can implement 2 classes, We can implement 2 classes, MultiThreadedEchoServerMultiThreadedEchoServer and and ThreadedEchoHandlerThreadedEchoHandler to handle multiple to handle multiple client connectionsclient connections MultiThreadedEchoServerMultiThreadedEchoServer creates creates

ThreadedEchoHandlerThreadedEchoHandler objects for each objects for each clientclient

ThreadedEchoHandlerThreadedEchoHandler extends extends Thread Thread and its and its run()run() method handles client I/O method handles client I/OIts implementation is the same as the Its implementation is the same as the

mainmain method of the method of the EchoServerEchoServer class class

Page 27: EE2E1. JAVA Programming Lecture 9 Network Programming

MultiThreadedEchoServerMultiThreadedEchoServer objectobject

Telnet Telnet Telnet

ThreadedEchoHandler ThreadedEchoHandler objectobject

ThreadedEchoHandler ThreadedEchoHandler objectobject

ThreadedEchoHandler ThreadedEchoHandler objectobject

Page 28: EE2E1. JAVA Programming Lecture 9 Network Programming

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){} }}

Page 29: EE2E1. JAVA Programming Lecture 9 Network Programming

An email program

As a simple example of socket As a simple example of socket programming we can implement a program programming we can implement a program that sends email to a remote sitethat sends email to a remote site This is taken from This is taken from Core JavaCore Java, vol 2, , vol 2,

chapter 3chapter 3 Email servers use port number 25 which is Email servers use port number 25 which is

the SMTP portthe SMTP port Simple mail transport protocolSimple mail transport protocol

Page 30: EE2E1. JAVA Programming Lecture 9 Network Programming

A client socket to the mail server can be A client socket to the mail server can be opened on port 25opened on port 25

SMPT uses the following protocolSMPT uses the following protocol

Socket s=new Socket(“engmail.bham.ac.uk”,25);

HELO sending hostMAIL FROM:sender email addressRCPT TO: recipient email addressDATAmail message….QUIT

Page 31: EE2E1. JAVA Programming Lecture 9 Network Programming

The email program uses a simple GUI to The email program uses a simple GUI to input the required information input the required information

The The sendsend button on the GUI calls the button on the GUI calls the sendMail() sendMail() method which outputs the method which outputs the correct protocol to the mail servercorrect 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

Page 32: EE2E1. JAVA Programming Lecture 9 Network Programming
Page 33: EE2E1. JAVA Programming Lecture 9 Network Programming
Page 34: EE2E1. JAVA Programming Lecture 9 Network Programming

URL connections

We have seen that to send or retrieve information We have seen that to send or retrieve information to a web server, we use the HTTP protocol to a web server, we use the HTTP protocol through a client socket attached to port 80through a client socket attached to port 80

We can do this by using normal socket-based We can do this by using normal socket-based programming and sending the correct HTTP programming and sending the correct HTTP commandscommands

However, Java has specific support for the HTTP However, Java has specific support for the HTTP protocol through its protocol through its URLConnectionURLConnection class class Its very easy to retrieve a file from a web server Its very easy to retrieve a file from a web server

by simply providing the file’s by simply providing the file’s urlurl as a string as a string

Page 35: EE2E1. JAVA Programming Lecture 9 Network Programming

This sets up an input stream from a This sets up an input stream from a urlurl connection connection Can turn this into a Can turn this into a Scanner Scanner object for text object for text

processingprocessing The The URLConnectionURLConnection class also has additional class also has additional

functionality related to the HTTP protocolfunctionality related to the HTTP protocol Querying the server for header informationQuerying the server for header information Setting request propertiesSetting request properties

URL u=new URL(“http://www.bham.ac.uk”);

URLConnection c=u.openConnection();

InputStream in=c.getInputStream();

Page 36: EE2E1. JAVA Programming Lecture 9 Network Programming

The following simple example program The following simple example program opens a web page and displays the HTMLopens a web page and displays the HTML

It also checks the server response codeIt also checks the server response code 404 if the page is not found404 if the page is not found 200 if the connection succeeded200 if the connection succeeded

Uses a Uses a ScannerScanner object to output the lines of object to output the lines of HTMLHTML

Page 37: EE2E1. JAVA Programming Lecture 9 Network Programming

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);

} }

}

Page 38: EE2E1. JAVA Programming Lecture 9 Network Programming
Page 39: EE2E1. JAVA Programming Lecture 9 Network Programming

Advanced networking technologies in Java

In this section we will look briefly at more In this section we will look briefly at more advanced technologies for networking in advanced technologies for networking in Java without looking in detail at codeJava without looking in detail at code Sending data to a web serverSending data to a web server

CGI and servlet technologyCGI and servlet technology Inter-object communicationInter-object communication

Remote method invocation (RMI) Remote method invocation (RMI) CORBACORBA

Page 40: EE2E1. JAVA Programming Lecture 9 Network Programming

CGI and servlet technology We often need to send data back to a web serverWe often need to send data back to a web server

Typically we fill out an online form displayed on Typically we fill out an online form displayed on a web browser and click a ‘submit’ buttona web browser and click a ‘submit’ button

Older web technology uses a CGI script to Older web technology uses a CGI script to process the informationprocess the information

CGI stands for Common Gateway InterfaceCGI stands for Common Gateway InterfaceTypically it is a program running on the server Typically it is a program running on the server

and written in a scripting language like Perland written in a scripting language like PerlThe CGI script processes the data submitted The CGI script processes the data submitted

and sends back a response to the client – and sends back a response to the client – usually a HTML pageusually a HTML page

Page 41: EE2E1. JAVA Programming Lecture 9 Network Programming

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

Page 42: EE2E1. JAVA Programming Lecture 9 Network Programming

CGI is well established and still widely CGI is well established and still widely used technologyused technology

Its major disadvantage is that each request Its major disadvantage is that each request forks a new process which can make it slowforks a new process which can make it slow Makes sharing resources trickyMakes sharing resources tricky

Also there are some security flaws with Also there are some security flaws with CGI – it can be fooled into running CGI – it can be fooled into running commands on the server since it uses an commands on the server since it uses an interpreted scripted languageinterpreted scripted language

Page 43: EE2E1. JAVA Programming Lecture 9 Network Programming

ServletsServlets are Java classes which extend the are Java classes which extend the HttpServletHttpServlet class. They run inside a class. They run inside a Servlet Servlet ContainerContainer which calls methods of the servlet which calls methods of the servlet The servlet container must be part of a The servlet container must be part of a

compliant web server which contains the Java compliant web server which contains the Java runtime environmentruntime environment

They run in the Java virtual machine inside the They run in the Java virtual machine inside the web server and so are portable and secureweb server and so are portable and secure

Unlike CGI each separate request creates a new Unlike CGI each separate request creates a new thread which is able to share resources with thread which is able to share resources with existing running threadsexisting running threads

Page 44: EE2E1. JAVA Programming Lecture 9 Network Programming

Inter-object communication Object orientation is all about objects Object orientation is all about objects

‘communicating’ with each other by calling ‘communicating’ with each other by calling each others’ methodseach others’ methods What if the objects are distributed across What if the objects are distributed across

a network?a network? What if the objects are implemented in What if the objects are implemented in

different languages? (eg Java and C++)different languages? (eg Java and C++)

Page 45: EE2E1. JAVA Programming Lecture 9 Network Programming

There are two mechanisms for inter object There are two mechanisms for inter object communication across a networkcommunication across a network Language independent mechanism is called Language independent mechanism is called

CORBACORBACommon object request brokerCommon object request brokerA separate language neutral A separate language neutral broker objectbroker object

handles all messages between the objectshandles all messages between the objectsGenerally rather slow and complex because Generally rather slow and complex because

of its generality and ability to handle legacy of its generality and ability to handle legacy codecode

If both objects are implemented in Java a much If both objects are implemented in Java a much simpler mechanism is simpler mechanism is Remote Method Remote Method Invocation Invocation (RMI)(RMI)

Page 46: EE2E1. JAVA Programming Lecture 9 Network Programming

In RMI, a In RMI, a client client object calls a method of a object calls a method of a serverserver object on a different machine object on a different machine Client/server terminology only applies to Client/server terminology only applies to

the single method callthe single method call

Client object

Server object

Method call with parameters

Returned data (objects)

Page 47: EE2E1. JAVA Programming Lecture 9 Network Programming

All this seems easy but the actual behind the scenes All this seems easy but the actual behind the scenes issues are complexissues are complex Actual inter-object communictation is done Actual inter-object communictation is done

through separate through separate stubstub objects which package objects which package remote method calls and parametersremote method calls and parameters

The server registers its objects with a naming The server registers its objects with a naming serviceservice

The clients finds the remote objects using a url : The clients finds the remote objects using a url : “rmi://servername.com/”“rmi://servername.com/”

There are complex security issues involved also There are complex security issues involved also as calling a remote method locally can introduce as calling a remote method locally can introduce virusesviruses

However, much of this is transparent to the However, much of this is transparent to the programmer and RMI is relatively straighforwardprogrammer and RMI is relatively straighforward

Page 48: EE2E1. JAVA Programming Lecture 9 Network Programming

And finally…..

Network programming is a doddle in JavaNetwork programming is a doddle in Java Sockets look like ordinary I/O streams from Sockets look like ordinary I/O streams from

an application programming viewpointan application programming viewpoint The main issues are writing multi-threaded The main issues are writing multi-threaded

code for multiple client applicationscode for multiple client applications In the last lab exercise, you will have the In the last lab exercise, you will have the

opportunity to write a multi-threading opportunity to write a multi-threading server for a network-based game!server for a network-based game!

Page 49: EE2E1. JAVA Programming Lecture 9 Network Programming

A very early ……..

Merry Christmas!!