15
Lecture 9 Lecture 9 Network programming Network programming

Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Embed Size (px)

Citation preview

Page 1: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Lecture 9Lecture 9

Network programmingNetwork programming

Page 2: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Manipulating URLsManipulating URLs

URL is an acronym for URL is an acronym for Uniform Resource LocatorUniform Resource Locator and is a reference and is a reference (an address) to a resource on the Internet. (an address) to a resource on the Internet.

Sample structure of a URL. The resource name part may contain: Sample structure of a URL. The resource name part may contain: host name, file name, port number(optional) and reference host name, file name, port number(optional) and reference (optional)(optional)

httphttp://://java.sun.comjava.sun.com

you can create a URL object in Java from an absolute URL or a you can create a URL object in Java from an absolute URL or a relative URL.relative URL.

The URL class provides several methods implemented on URL The URL class provides several methods implemented on URL objects. You can get the protocol, host name, port number, and objects. You can get the protocol, host name, port number, and filename from a URL.filename from a URL.

Protocol Identifier Resource Name

Page 3: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Example codeExample code

import java.net.*; import java.net.*; import java.io.*; import java.io.*; public class ParseURL { public class ParseURL { public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { URL aURL = new URL("http://java.sun.com:80/docs/books/" + URL aURL = new URL("http://java.sun.com:80/docs/books/" + "tutorial/index.html#DOWNLOADING");"tutorial/index.html#DOWNLOADING"); System.out.println("protocol = " +System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " +aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " +aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " +aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " +aURL.getPort()); System.out.println("ref = " + aURL.getRef()); aURL.getRef()); }}} }

Output of the above code:Output of the above code:

protocol = httpprotocol = httphost = java.sun.comhost = java.sun.comfilename = /docs/books/tutorial/index.htmlfilename = /docs/books/tutorial/index.htmlport = 80port = 80ref = DOWNLOADINGref = DOWNLOADING

Page 4: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Connecting with a URL (1)Connecting with a URL (1) openStream()openStream(): returns a : returns a java.io.InputStream java.io.InputStream object, from object, from

which you can read easily as reading from an input stream. It may which you can read easily as reading from an input stream. It may throw an IOExceptionthrow an IOExceptionExample codeExample codeimport java.net.*;import java.net.*;import java.io.*;import java.io.*;

public class ReadURL {public class ReadURL { public static void main(String[] args) throws Exception {public static void main(String[] args) throws Exception {

URL osu = new URL("http://www.osu.edu/");URL osu = new URL("http://www.osu.edu/");BufferedReader in = new BufferedReader( BufferedReader in = new BufferedReader(

new new InputStreamReader(osu.openStream()));InputStreamReader(osu.openStream()));

String inputLine;String inputLine;

while ((inputLine = in.readLine()) != null)while ((inputLine = in.readLine()) != null) System.out.println(inputLine);System.out.println(inputLine);

in.close();in.close(); }}}}

This prints out the source code for the webpage This prints out the source code for the webpage www.osu.eduwww.osu.edu

Page 5: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Connecting with a URL (2)Connecting with a URL (2)

openConnection()openConnection(): Returns a : Returns a URLConnectionURLConnection object that object that represents a connection to the remote object referred to by the URL. represents a connection to the remote object referred to by the URL. It may throws an IOExceptionIt may throws an IOException

try {try { URL osu = new URL("http://www.osu.edu/");URL osu = new URL("http://www.osu.edu/"); URLConnection osuConnection = osu.openConnection();URLConnection osuConnection = osu.openConnection();} catch (MalformedURLException e) { // new URL() failed} catch (MalformedURLException e) { // new URL() failed . . .. . .} catch (IOException e) {} catch (IOException e) { . . .. . .}}

The The URLConnectionURLConnection class provides many methods to communicate class provides many methods to communicate with the URL, such as reading and writing.with the URL, such as reading and writing.

Page 6: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

SocketsSockets

Sometimes you need a low-level network communication, such as Sometimes you need a low-level network communication, such as a client-server applicationa client-server application

The TCP protocol provides a reliable point-to-point communication The TCP protocol provides a reliable point-to-point communication channel via the sockets.channel via the sockets.

A socket is an endpoint for reliable communication between two A socket is an endpoint for reliable communication between two machines. To connect with each other, each of the client and the machines. To connect with each other, each of the client and the server binds a socket to its end for reading and writing.server binds a socket to its end for reading and writing.

The The java.netjava.net package provides two classes — package provides two classes — SocketSocket and and ServerSocketServerSocket — to implement the client and the server, — to implement the client and the server,

respectively.respectively.

Page 7: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Establishing a simple serverEstablishing a simple server Five steps:Five steps:

1).1). Create a Create a ServerSocketServerSocket object objectServerSocket server=new ServerSocket server=new ServerSocket(port,queueLength);ServerSocket(port,queueLength);

2).2). The server listens indefinitely (or blocks) for an attempt by a The server listens indefinitely (or blocks) for an attempt by a client to client to connectconnect

Socket connection = server.accept();Socket connection = server.accept();

3).3). Get the Get the OutputStreamOutputStream and and InputStreamInputStream objects that objects that enable the enable the server to communicate with the client by sending and server to communicate with the client by sending and receiving bytesreceiving bytes

InputStream input = connection.getInputStream();InputStream input = connection.getInputStream();OutputStream output = connection.getOutputStream();OutputStream output = connection.getOutputStream();

* You can get a stream of other data types from the * You can get a stream of other data types from the InputStreamInputStream and and OutputStreamOutputStream

4).4). Processing phaseProcessing phase: the server and the client communicate via : the server and the client communicate via the the InputStreamInputStream and the and the OutputStreamOutputStream objects objects

5).5). After the communication completes, the server closes the After the communication completes, the server closes the connection connection by invoking by invoking close()close() on the on the SocketSocket and the and the corresponding streamscorresponding streams

Page 8: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Establishing a simple clientEstablishing a simple client

Four steps:Four steps:

1).1). Create a Create a SocketSocket object object Socket connection = new Socket (serverAddress, port);Socket connection = new Socket (serverAddress, port);

2).2). Get the Get the OutputStreamOutputStream and and InputStreamInputStream of the Socket. of the Socket. The The server and the client must send and receive the data in the server and the client must send and receive the data in the same same formatformat

3).3). Processing phaseProcessing phase: the server and the client communicate via : the server and the client communicate via the the InputStreamInputStream and the and the OutputStreamOutputStream objects objects

4).4). After the communication completes, the client closes the After the communication completes, the client closes the connection.connection.

Page 9: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

The server sideThe server side

import java.lang.*;import java.lang.*;import java.io.*;import java.io.*;import java.net.*;import java.net.*;

class Server {class Server { public static void main(String args[]) {public static void main(String args[]) { String data = "Let's test if we can connect...";String data = "Let's test if we can connect..."; try {try { ServerSocket server_socket = new ServerSocket(1234);ServerSocket server_socket = new ServerSocket(1234); System.out.println("I’ve started, dear clients...");System.out.println("I’ve started, dear clients...");

Socket socket = server_socket.accept();Socket socket = server_socket.accept();

System.out.print("Server has connected!\n");System.out.print("Server has connected!\n"); PrintWriter outToClient = new PrintWriter outToClient = new

PrintWriter(socket.getOutputStream(), true);PrintWriter(socket.getOutputStream(), true);

System.out.print("Sending string: ‘" + data + “’\n");System.out.print("Sending string: ‘" + data + “’\n"); outToClient.print(data);outToClient.print(data);

outToClient.close();outToClient.close(); socket.close();socket.close(); server_socket.close();server_socket.close(); }} catch(Exception e) {catch(Exception e) { System.out.print("Whoops! It didn't work!\n");System.out.print("Whoops! It didn't work!\n"); }} }}}}

(this example is got from (this example is got from http://www.cise.ufl.edu/~amyles/tcpchat/http://www.cise.ufl.edu/~amyles/tcpchat/))

A simple server/client pair exampleA simple server/client pair example

Page 10: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

A simple server/client pair example (cont.)A simple server/client pair example (cont.)The client sideThe client side

import java.lang.*;import java.lang.*;import java.io.*;import java.io.*;import java.net.*;import java.net.*;

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

try {try { Socket socket = new Socket("localhost", 1234);Socket socket = new Socket("localhost", 1234);

BufferedReader inFromServer = new BufferedReader(newBufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));InputStreamReader(socket.getInputStream()));

System.out.print("Received string: ‘");System.out.print("Received string: ‘"); while (inFromServer.ready()) while (inFromServer.ready()) System.out.println(in.readLine()); //Read one line and output itSystem.out.println(in.readLine()); //Read one line and output it

inFromServer.close();inFromServer.close(); }} catch(Exception e) {catch(Exception e) {

System.out.print("Whoops! It didn't work!\n");System.out.print("Whoops! It didn't work!\n"); }} }}}}

(this example is got from (this example is got from http://www.cise.ufl.edu/~amyles/tcpchat/http://www.cise.ufl.edu/~amyles/tcpchat/))

Page 11: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

A simple server/client pair example (cont.)A simple server/client pair example (cont.) What happens on the screen if you run the code?What happens on the screen if you run the code?

First run First run Server.javaServer.java

Then run Then run Client.javaClient.java

Page 12: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

A simple server/client pair example (cont.)A simple server/client pair example (cont.)

If you run If you run Client.javaClient.java without running without running Server.javaServer.java

Page 13: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

DatagramsDatagrams

The UDP protocol provides a mode of network communication The UDP protocol provides a mode of network communication whereby whereby datagramsdatagrams are sent over the network. are sent over the network. DatagramSocketDatagramSockets s are used for the connection.are used for the connection.

A datagram’s arrival, arrival time and order of arrival is not A datagram’s arrival, arrival time and order of arrival is not guaranteed. It’s used whenever an information needs to be guaranteed. It’s used whenever an information needs to be broadcast periodicallybroadcast periodically

Page 14: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

UDP exampleUDP example

import java.net.*;import java.net.*;

class GetDate {class GetDate { final static int PORT_DAYTIME = 13;final static int PORT_DAYTIME = 13; public static void main(String[] args) throws Exception {public static void main(String[] args) throws Exception { DatagramSocket dgsocket = new DatagramSocket();DatagramSocket dgsocket = new DatagramSocket(); InetAddress destination = InetAddress destination =

InetAddress.getByName("news.cis.ohio-state.edu");;InetAddress.getByName("news.cis.ohio-state.edu");; DatagramPacket datagram;DatagramPacket datagram; byte[] msg = new byte[256];byte[] msg = new byte[256];

datagram = new DatagramPacket(msg, msg.length, destination, datagram = new DatagramPacket(msg, msg.length, destination, PORT_DAYTIME);PORT_DAYTIME);

dgsocket.send(datagram);dgsocket.send(datagram);

datagram = new DatagramPacket(msg, msg.length);datagram = new DatagramPacket(msg, msg.length); dgsocket.receive(datagram);dgsocket.receive(datagram);

String received = new String(datagram.getData());String received = new String(datagram.getData()); System.out.println("Time of machine:" + received);System.out.println("Time of machine:" + received);

dgsocket.close();dgsocket.close(); }}}}

Sample excution: Sample excution: alpha> java GetDatealpha> java GetDateTime of machine: Tue May 24 00:16:42 2005Time of machine: Tue May 24 00:16:42 2005

Page 15: Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet

Supplemental readingSupplemental reading

Custom networkingCustom networkinghttp://java.sun.com/docs/books/tutorial/networking/index.htmlhttp://java.sun.com/docs/books/tutorial/networking/index.html

JavaTM Programming Language Basics, Socket CommunicationsJavaTM Programming Language Basics, Socket Communications

http://developer.java.sun.com/developer/onlineTraining/Programming/BasicJhttp://developer.java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.htmlava2/socket.html