java net Chapter 3 Net Working Outline Networking

  • Slides: 86
Download presentation
java. net Chapter 3 Net. Working

java. net Chapter 3 Net. Working

Outline: Networking • Presents the network programming in Java language. • Main points: 1)

Outline: Networking • Presents the network programming in Java language. • Main points: 1) Discuss the usage of java. net package. 2) Introduce the Java implementation for UDP protocol. 3) Introduce the New I/O API.

Why Java Why use Java for Networking? a) Java was the first programming language

Why Java Why use Java for Networking? a) Java was the first programming language designed from the ground up with networking in mind. b) Java provides easy solutions to two crucial problem for Internet networking — platform independence and security. c) It is far easier to write network programs in Java than in almost any other language. d) In the fully functional applications, very little code is devoted to networking.

Internet Addressing • Internet address ( IP address) is a unique number for identifying

Internet Addressing • Internet address ( IP address) is a unique number for identifying a device connected to the Internet. • The current standard is IPv 4 which are four bytes long. • The hostname and IP address is, in Java, represented by java. net. Inet. Address. • Inet. Address is used by many other networking classes, including Socket, Server. Socket, URL, Datagram. Socket, Datagram. Packet, and more.

Inet. Address Class • No public constructor • Three static methods: • Inet. Address

Inet. Address Class • No public constructor • Three static methods: • Inet. Address get. By. Name(String) • Static method used to retrieve the address for the host name passed as the parameter. • Inet. Address [ ] get. All. By. Name(String) • Static method used to retrieve all the addresses for the host name passed as a parameter. • Inet. Address get. Local. Host( ) • Static method used to retrieve the address for the current, or local, host.

Inet. Address Class • Useful methods • String get. Host. Name( ) • Returns

Inet. Address Class • Useful methods • String get. Host. Name( ) • Returns the host name. • byte[ ] get. Address( ) • Returns the IP address. • String get. Host. Address( ) • Returns the IP address as a string.

Inet. Address Examples import java. net. *; public class IISTBy. Name{ public static void

Inet. Address Examples import java. net. *; public class IISTBy. Name{ public static void main(String [ ] args){ try { Inet. Address address = Inet. Address. get. By. Name(args[0]); System. out. println(address); } catch (Unkown. Host. Exception ex){ System. out. println(“Could not find ” + args[0]); } } }

The URL Class • The java. net. URL is an abstraction of a Uniform

The URL Class • The java. net. URL is an abstraction of a Uniform Resource Locator (URL). • URLs are composed of five pieces: 1. The scheme, also known as the protocol 2. The authority 3. The path 4. The query string 5. The fragment identifier, also known as the section or ref <scheme>: //<authority><path>? <query>#<fragment>

The URL Class For example, given the URL : http: //www. ibiblio. org/javafaq/javabooks/index. html?

The URL Class For example, given the URL : http: //www. ibiblio. org/javafaq/javabooks/index. html? is bn=123456789#toc 1. scheme : http 2. authority : www. ibiblio. org 3. path : /javafaq/books/javabooks/index. html 4. query string : isbn=123456789 5. fragment identifier : toc

The URL Class • The authority may further be divided into the user info,

The URL Class • The authority may further be divided into the user info, the host, and the port. • For example, in the URL http: //admin@www. blackstar. com: 8080/ 1. user info : admin 2. host : www. blackstar. com 3. port : 8080

The URL Class • The java. net. URL class provides static methods for getting

The URL Class • The java. net. URL class provides static methods for getting the above mentioned information: • a) get. File( ) // path + query • b) get. Host() • c) get. Port( ) • d) get. Protocol() • e) get. Ref() • f) get. Query( ) • g) get. Path( ) • h) get. User. Info( ) • i) get. Authority( )

URL Class - Constructors • URL(String spec) • Creates a URL object from the

URL Class - Constructors • URL(String spec) • Creates a URL object from the String representation. • URL(String protocol, String host, int port, String file) • Creates a URL object from the specified protocol, host, port number, and file. • URL(String protocol, String host, String file) • Creates a URL from the specified protocol name, host name, and file name. • …

Example 1 import java. net. *; public class Protocol. Tester{ public static void test.

Example 1 import java. net. *; public class Protocol. Tester{ public static void test. Protocol(String url){ try { URL u = new URL (url); System. out. println(u. get. Protocol() + “ is supported”); } catch (Malformed. URLException ex){ String protocol = url. substring(0, url. index. Of(‘: ’)); System. out. println(protocol + “ is not supported”); } } }

Example 1 You can test it with the following Tester public class Tester {

Example 1 You can test it with the following Tester public class Tester { public static void main(String [ ] args) { Protocol. Tester. test. Protocol (“http: //www. adc. org”); Protocol. Tester. test. Protocol (“http: //www. amazon. com/exec/obidos/order 2”); Protocol. Tester. test. Protocol (“ftp: //metalab. unc. edu/pub/languages/javafap”); } }

LAB Work: URL

LAB Work: URL

Retrieving Data from a URL Procedure to use the methods: 1) Create an URL

Retrieving Data from a URL Procedure to use the methods: 1) Create an URL object • e. g. URL u = new URL("http: //www. iist. unu. edu"); 2) Open an Input. Stream object directly from the URL object e. g. Input. Stream in = u. open. Stream( ); 3) Or open an URLConnection object from the URL object and then get an Input. Stream object from the URLConnection object. • e. g. URLConnection uc = u. open. Connection( ); Input. Stream in = uc. get. Input. Stream( ); 4) In either case, you will have an Input. Stream. What’s followed is the normal I/O procedure for getting data. 5) Don’t forget to put the try catch block for catching the Malformed. URLException and IOException.

Retrieving Data from a URL What is the difference between using the open. Stream

Retrieving Data from a URL What is the difference between using the open. Stream and open. Connection method? 1) open. Stream method only give you the access to the raw data and cannot detect the encoding information. 2) open. Connection method opens a socket to the specified URL and returns a URLConnection object. 3) The URLConnection object gives you access to everything sent by the server. You can access all the metadata specified by the protocol such as the scheme. The URLConnection class also lets you write data to as well as read from a URL.

Retrieving Data from a URL • The following methods are used to access the

Retrieving Data from a URL • The following methods are used to access the header fields and the contents after the connection is made to the remote object: 1) get. Content 2) get. Header. Field 3) get. Input. Stream 4) get. Output. Stream

Retrieving Data from a URL • Certain header fields are accessed frequently. The methods:

Retrieving Data from a URL • Certain header fields are accessed frequently. The methods: 1) get. Content. Encoding 2) get. Content. Length 3) get. Content. Type 4) get. Date 5) get. Expiration 6) get. Last. Modified

Example: Reading from URL import java. net. *; Import java. io. *; Public class

Example: Reading from URL import java. net. *; Import java. io. *; Public class URLConnection. Reader{ public static void main(String [] args) throws Exception { URL yahoo = new URL(“http: //www. yahoo. com”); URLConnection yc = yahoo. open. Connection(); Buffered. Reader in = new Buffered. Reader (new Input. Stream. Reader(yc. get. Input. Stream())); String input. Line; while ((input. Line = in. read. Line()) !=null) System. out. println(input. Line); in. close(); } }

Uniform Resource Identifier URI • A Uniform Resource Identifier (URI) is an abstraction of

Uniform Resource Identifier URI • A Uniform Resource Identifier (URI) is an abstraction of a URL. • Most URIs used in practice are URLs, but most specifications and standards such as XML are defined in terms of URIs • In Java 1. 4 and later, URIs are represented by the java. net. URI class. • you should use the URL class when you want to download the content of a URL and the URI class when you want to use the URI for identification rather than retrieval. • When you need to do both, you may convert from a URI to a URL with the to. URL( ) method, and in Java 1. 5 you can also convert from a URL to a URI using the to. URI( ) method of the URL class.

Uniform Resource Identifier URI • A URI reference has up to three parts: a

Uniform Resource Identifier URI • A URI reference has up to three parts: a scheme, a schemespecific part, and a fragment identifier. The general format is: scheme-specific-part : fragment. • Getter methods: 1) public String get. Scheme( ) 2) public String get. Scheme. Specific. Part( ) 3) public String get. Raw. Scheme. Specific. Part( ) 4) public String get. Fragment( ) 5) public String get. Raw. Fragment( )

Socket Communication • A server (program) runs on a specific computer and has a

Socket Communication • A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request. port server Connection request Client

Socket Communication • If everything goes well, the server accepts the connection. Upon acceptance,

Socket Communication • If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. Connection port server Client

Sockets and Java Socket Classes • A socket is an endpoint of a two-way

Sockets and Java Socket Classes • A socket is an endpoint of a two-way communication link between two programs running on the network. • A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent. • Java’s. net package provides two classes: • Socket – for implementing a client • Server. Socket – for implementing a server

Java Sockets Server. Socket(1234) Output/write stream Client Input/read stream Socket(“ 128. 250. 25. 158”,

Java Sockets Server. Socket(1234) Output/write stream Client Input/read stream Socket(“ 128. 250. 25. 158”, 1234) It can be host_name like “mandroo. cs. mu. oz. au”

Implementing a Server 1. Open the Server Socket: Server. Socket server; Print. Writer os;

Implementing a Server 1. Open the Server Socket: Server. Socket server; Print. Writer os; server = new Server. Socket(PORT); 2. Wait for the Client Request: Socket client = server. accept();

Implementing a Server 3. Create I/O streams for communicating to the client os =

Implementing a Server 3. Create I/O streams for communicating to the client os = new Print. Writer ( client. get. Output. Stream()); Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(client. get. Input. Stream())); 4. Perform communication with client Receive from client: String line = in. read. Line(); Send to client: os. println("Hellon"); 5. Close sockets: client. close();

Implementing a Server For multithreaded server: while(true) { i. wait for client requests (step

Implementing a Server For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with “client” socket as parameter (the thread creates streams (as in step (3) and does communication as stated in (4). Remove thread once service is provided. }

Server. Socket – methods • accept( ) – accepts a connection request and creates

Server. Socket – methods • accept( ) – accepts a connection request and creates a socket to the remote user • close( ) – close the server socket and wait for next connection request

Example Echo. Server. java Refer the material of slides_distr pro. pdf (page 197 -201)

Example Echo. Server. java Refer the material of slides_distr pro. pdf (page 197 -201)

Server. Socket – Life cycle • A new Server. Socket is created on a

Server. Socket – Life cycle • A new Server. Socket is created on a particular port using a Server. Socket( ) constructor. • The Server. Socket listens for incoming connection attempts on that port using its accept( ) method. accept( ) blocks until a client attempts to make a connection, at which point accept( ) returns a Socket object connecting the client and the server. • Depending on the type of server, either the Socket's get. Input. Stream( ) method, get. Output. Stream( ) method, or both are called to get input and output streams that communicate with the client.

Server. Socket – Life cycle • The server and the client interact according to

Server. Socket – Life cycle • The server and the client interact according to an agreed-upon protocol until it is time to close the connection. • The server, the client, or both close the connection. • The server returns to step 2 and waits for the next connection.

Server. Socket server = new Server. Socket(8888); Server. Socket example Socket client = server.

Server. Socket server = new Server. Socket(8888); Server. Socket example Socket client = server. accept(); Print. Writer pw = new Print. Writer(client. get. Output. Stream()); Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader (client. get. Input. Stream())); String st; boolean ketthuc = false; do{ st=br. read. Line(); if (st. equals. Ignore. Case("bye")) { ketthuc=true; } Scanner scn = new Scanner(System. in); pw. println(scn. next. Line()); pw. flush(); } while (!ketthuc);

Implementing a Client 1. Create a Socket Object: client = new Socket(server, port_id); 2.

Implementing a Client 1. Create a Socket Object: client = new Socket(server, port_id); 2. Create I/O streams for communicating with the server. os = new Print. Writer (client. get. Output. Stream()); Buffered. Reader is = new Buffered. Reader(new Input. Stream. Reader(client. get. Input. Stream())) 3. Perform I/O or communication with the server: • Receive data from the server: String line = is. read. Line(); • Send data to the server: os. println("Hellon"); 4. Close the socket when done: client. close();

Example Echo. Client. java Refer the material of slides_distr pro. pdf (page 203 -206)

Example Echo. Client. java Refer the material of slides_distr pro. pdf (page 203 -206)

Socket server = new Socket(IPServer, 8888); Print. Writer pw-=example new Print. Writer (server. get.

Socket server = new Socket(IPServer, 8888); Print. Writer pw-=example new Print. Writer (server. get. Output. Stream(), true); Client. Socket Buffered. Reader br = new Buffered. Reader (new Input. Stream. Reader rver. get. Input. Stream())); String st; boolean ketthuc = false; do { //Gui thong tin Scanner scn = new Scanner(System. in); pw. write(scn. next. Line()); pw. write("n"); pw. flush(); //Nhan thong tin st=br. read. Line(); System. out. println(st); if (st. equals. Ignore. Case("bye")) { ketthuc=true; } } while (!ketthuc);

Echo. Server. java public class Echo. Server { public static void main(String[] args) throws

Echo. Server. java public class Echo. Server { public static void main(String[] args) throws IOException { Server. Socket server. Socket = null; server. Socket = new Server. Socket(10007); Socket client. Socket = null; client. Socket = server. Socket. accept();

Echo. Server. java Print. Writer out = new Print. Writer(client. Socket. get. Output. Stream());

Echo. Server. java Print. Writer out = new Print. Writer(client. Socket. get. Output. Stream()); Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(client. Socket. get. Input. Stream())); String input. Line; while ((input. Line = in. read. Line()) != null) { System. out. println ("Server: " + input. Line); out. println(input. Line); if (input. Line. equals("Bye. ")) break; } out. close(); in. close(); client. Socket. close(); server. Socket. close();

Echo. Client. java public class Echo. Client { public static void main(String[] args) throws

Echo. Client. java public class Echo. Client { public static void main(String[] args) throws IOException { String server. Hostname = new String ("127. 0. 0. 1"); Socket echo. Socket = null; Print. Writer out = null; Buffered. Reader in = null; echo. Socket = new Socket(server. Hostname, 10007); //out put result to server out = new Print. Writer(echo. Socket. get. Output. Stream(), true); //get input from the Server in = new Buffered. Reader(new Input. Stream. Reader(echo. Socket. get. Input. Stream()));

Echo. Client. java Buffered. Reader std. In = new Buffered. Reader( new Input. Stream.

Echo. Client. java Buffered. Reader std. In = new Buffered. Reader( new Input. Stream. Reader(System. in)); String user. Input; System. out. print ("input: "); while ((user. Input = std. In. read. Line()) != null) { out. println(user. Input); System. out. println("echo: " + in. read. Line()); System. out. print ("input: "); } out. close(); in. close(); std. In. close(); echo. Socket. close(); } }

LAB Work: Chating program

LAB Work: Chating program

User Datagram Protocol • The User Datagram Protocol (UDP) is an alternative protocol for

User Datagram Protocol • The User Datagram Protocol (UDP) is an alternative protocol for sending data over IP • UDP is very quick, but not reliable. • Java's implementation of UDP is split into two classes: Datagram. Packet and Datagram. Socket. • The Datagram. Packet class stuffs bytes of data into UDP packets called datagrams and lets you unstuff datagrams that you receive. • A Datagram. Socket sends as well as receives UDP datagrams.

Constructors for Datagram. Packet

Constructors for Datagram. Packet

Constructors for Datagram. Socket

Constructors for Datagram. Socket

Sending and Receiving

Sending and Receiving

LAB Work: UDP 1) Write a Echo. UDP server which will send back any

LAB Work: UDP 1) Write a Echo. UDP server which will send back any message received from client. 2)Write a UDPclient which sends some message to the Echo. UDP server for testing it.

Reference Socket Example http: //www. cs. uic. edu/~troy/spring 05 /cs 450/sockets/socket. html

Reference Socket Example http: //www. cs. uic. edu/~troy/spring 05 /cs 450/sockets/socket. html

Why NIO? • Allow Java programmers to implement high-speed I/O. • NIO deals with

Why NIO? • Allow Java programmers to implement high-speed I/O. • NIO deals with data in blocks which can be much faster than processing data by the (streamed) byte.

NIO Components 1) 2) 3) 4) 5) Buffers Channels Selectors Regular Expressions Character Set

NIO Components 1) 2) 3) 4) 5) Buffers Channels Selectors Regular Expressions Character Set Coding

Buffers • In the NIO library, all data is handled with buffers. • A

Buffers • In the NIO library, all data is handled with buffers. • A buffer is essentially an array. Generally, it is an array of bytes, but other kinds of arrays can be used. • A buffer also provides structured access to data and also keeps track of the system's read/write processes. Types: a) Byte. Buffer b) Char. Buffer c) Short. Buffer d) Int. Buffer e) Long. Buffer· f) Float. Buffer g) Double. Buffer

Channels • Channel is like a stream in original I/O. • You can read

Channels • Channel is like a stream in original I/O. • You can read a buffer from and write a buffer to a channel. Unlike streams, channels are bi-directional.

Read from file Codes for reading from a file: File. Input. Stream fin =

Read from file Codes for reading from a file: File. Input. Stream fin = new File. Input. Stream( "readandshow. txt"); File. Channel fc = fin. get. Channel(); Byte. Buffer buffer = Byte. Buffer. allocate(1024); f c. read(buffer);

 • import java. io. *; • import java. nio. channels. File. Channel; copy.

• import java. io. *; • import java. nio. channels. File. Channel; copy. File. Example. java • import java. nio. Byte. Buffer; • public class copy. File. Example { • public static void main(String []args) throws Exception • { • String source ="D: \java_examples\hello. txt"; • String des = "D: \java_examples\hello 2. txt"; • File. Input. Stream fis = new File. Input. Stream(source); • File. Output. Stream fos = new File. Output. Stream(des); • //Get the File. Channel of File. Input. Stream instance • File. Channel fci = fis. get. Channel(); • File. Channel fco = fos. get. Channel();

 • • Byte. Buffer buffer = Byte. Buffer. allocate(1024); copy. File. Example. java

• • Byte. Buffer buffer = Byte. Buffer. allocate(1024); copy. File. Example. java • while(true) { • int read = fci. read(buffer); • if(read == -1) • break; • // flip the buffer • buffer. flip(); • //write to the destination channel • fco. write(buffer); • // clear the buffer and user it for the next read process • buffer. clear(); • } • }

LAB Work: NIO Refer to the example, please use the NIO to create a

LAB Work: NIO Refer to the example, please use the NIO to create a program to write a String to a text file and store in your computer.

Server with NIO • Channels and buffers are really intended for server systems that

Server with NIO • Channels and buffers are really intended for server systems that need to process many simultaneous connections efficiently. • Handling servers requires the new selectors that allow the server to find all the connections that are ready to receive output or send input.

Asynchronous I/O • Asynchronous I/O is made possible in NIO with scalable sockets, which

Asynchronous I/O • Asynchronous I/O is made possible in NIO with scalable sockets, which consist of the following components: a) Selectable Channel - A channel that can be multiplexed b) Selector - A multiplexor of selectable channel c) Selection key - A token representing the registration of a selectable channel with a selector

Selectors, Keys and Channels

Selectors, Keys and Channels

The Selection Process 1) Create a Selector and register channels with it • Use

The Selection Process 1) Create a Selector and register channels with it • Use Open() method to create a Selector. • The register() method is on Selectable. Channel, not Selector 2) 3) Invoke select() method on the Selector object Retrieve the Selected Set of keys from the Selector • Selected set: Registered keys with non-empty Ready Sets • Keys = selector. selected. Keys()

The Selection Process 4) Iterate over the Selected Set a) Check each key's Ready

The Selection Process 4) Iterate over the Selected Set a) Check each key's Ready Set b) Remove the key from the Selected Set (iterator. remove()) * Bits in the Ready Sets are never reset while the key is in the Selected Set * The Selector never removes keys from the Selected Set — you must do so c) Service the channel (key. channel()) as appropriate (read, write, etc)

Example : NIO Server 1 Skeleton does for a simple server with NIO: //Open

Example : NIO Server 1 Skeleton does for a simple server with NIO: //Open a Server. Socket. Channel server. Channel = Server. Socket. Channel. open ( ); //make the Server. Socket. Channel non-blocking. //necessary for asynchronous i/o server. Channel. configure. Blocking(false); Server. Socket ss = server. Channel. socket( );

NIO Server // bind the socket to aspecific port ss. bind(new Inet. Socket. Address(PORT_NO));

NIO Server // bind the socket to aspecific port ss. bind(new Inet. Socket. Address(PORT_NO)); //Open the selector Selector selector = Selector. open( ); //use the channel's register() method to register the //Server. Socketchannel with the selector. server. Channel. register(selector, Selection. Key. OP_ACCEPT);

Example : Create NIO Server /*check whether anything is ready to be acted on,

Example : Create NIO Server /*check whether anything is ready to be acted on, call the selector's select() method. For a long-running server, this normally goesin an infinite loop: */ while (true) { try { selector. select( ); } catch (IOException ex) { ex. print. Stack. Trace( ); break; } }

Create NIO Server

Create NIO Server

Create NIO Server

Create NIO Server

Create NIO Server

Create NIO Server

Secure Sockets • Starting from JDK 1. 4, Java Secure Sockets Extension (JSSE) is

Secure Sockets • Starting from JDK 1. 4, Java Secure Sockets Extension (JSSE) is part of the standard distribution. • JSSE uses the Secure Sockets Layer (SSL) Version 3 and Transport Layer Security (TLS) protocols and their associated algorithms to secure network communications. • JSSE abstracts all the low-level details such as keys exchange, authentication, and data encryption. All you have to do is to send your data over the streams from the secured sockets obtained. .

Java Secure Socket. Extension The Java Secure Socket Extension is divided into four packages:

Java Secure Socket. Extension The Java Secure Socket Extension is divided into four packages: 1) javax. net. ssl : The abstract classes that define Java's API for secure network communication. 2) javax. net: The abstract socket factory classes used instead of constructors to create secure sockets. 3) javax. security. cert: A minimal set of classes for handling public key certificates that's needed for SSL in Java 1. 1. (In Java 1. 2 and later, the java. security. cert package should be used instead. ) 4) com. sun. net. ssl: The concrete classes that implement the encryption algorithms and protocols in Sun's reference implementation of the JSSE.

SSL Handshake

SSL Handshake

Secure Client Sockets 1

Secure Client Sockets 1

Secure Client Sockets 1

Secure Client Sockets 1

Secure Client Sockets

Secure Client Sockets

Secure Client Sockets

Secure Client Sockets

Secure Client Sockets

Secure Client Sockets

Secure Server Sockets

Secure Server Sockets

Secure Server Sockets

Secure Server Sockets

Secure Server Socket

Secure Server Socket

Example Secure Server Socket • http: //www. herongyang. com/JDK/

Example Secure Server Socket • http: //www. herongyang. com/JDK/

Example: Sending Email • E-mail is sent by socket communication with port 25 on

Example: Sending Email • E-mail is sent by socket communication with port 25 on a computer system. • open a socket connected to port 25 on some system, and speak “mail protocol” to the daemon at the other end.

Example: Sending Email

Example: Sending Email

Example: Sending Email

Example: Sending Email

Example: Sending Email

Example: Sending Email

Example: Sending Email

Example: Sending Email

What will happen when you try to compile and run the following code import

What will happen when you try to compile and run the following code import java. io. *; public class URLConnection. Reader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http: //www. yahoo. com/"); URLConnection yc = yahoo. open. Connection(); Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(yc. get. Input. Stream())); String input. Line while ((input. Line = in. read. Line()) != null) System. out. println(input. Line); in. close();

What will happen when you try to compile and run the following code import

What will happen when you try to compile and run the following code import java. io. *; import java. net. *; public class URLConnection. Reader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http: //www. yahoo. com/"); URLConnection yc = yahoo. open. Connection(); Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader(yc. get. Input. Stream())); String input. Line ; while ((input. Line = in. read. Line()) != null) System. out. println(input. Line); in. close();