Post on 27-Dec-2015
Appendix F:Network Programming in Java
©SoftMoore Consulting Slide 1
Basic Network Concepts
• Packet (or datagram)– little bundle of information– sent from one node to another– each packet is delivered separately (possibly by different routes)
• Protocol– roles, vocabulary, rules for communication– network protocols (e.g., IP) versus application protocol (e.g.,
HTTP)
• IP– Internet Protocol– enables different local area networks to communicate– basis for connecting computers around the world
Slide 2©SoftMoore Consulting
Two Types of Information
• Application data– the information one computer wants to send to another
• Network protocol data– describes how to reach the intended computer– describes how to check for errors in the transmission
Slide 3©SoftMoore Consulting
TCP/IP: The Internet Protocol
Slide 4©SoftMoore Consulting
Physical Network
Transport Layer (TCP, UDP)
Internet Layer (IP)
Application Layer (HTTP, FTP, SMTP)
IP Addresses
• IP Address– identifies a host– serves as a destination address for a packet– IPv4 (most widely deployed)
• 4 bytes/32 bits for an IP address• Expressed using “dot” notation: 192.168.0.13
– IPv6 (the next generation)• 16 bytes/128 bits for an IP address
• Domain name– easy-to-remember name for a host– Example: www.google.com
• Domain Naming Service (DNS)– translates from domain names to IP addresses
Slide 5©SoftMoore Consulting
Socket
• Two-way connection
• Provides inter-process communication using IP
• Derived from BSD (UNIX) sockets
• Read/write streams between hosts– use either UDP and TCP protocols (layered on top of IP) – uses IP addresses and port numbers to locate servers
Slide 6©SoftMoore Consulting
Port
• Meeting place on a host– one service per port
• Port numbers identify services on a server
• Range from 1 to 65535 (use type int)
• Port numbers 1 through 255 are reserved for well-known services– HTTP is 80– TELNET is 23– etc.
• Port numbers less than 1024 are privileged
Slide 7©SoftMoore Consulting
Sockets and Ports (Diagram)
Slide 8©SoftMoore Consulting
Client
port 13
port 80
Time Service
Web Service
Socket
Server
Socket
Well-Known Ports
• 13: time
• 20,21: FTP
• 23: telnet
• 25: SMTP
• 43: whois
• 80: HTTP
• 119: NNTP
• 1099: RMI
Slide 9©SoftMoore Consulting
Time of Day Service
• From the command prompt, enter the following command:telnet time-A.timefreq.bldrdoc.gov 13
• Connects to the time-of-day service on a computer operated by the National Institute of Standards and Technology in Boulder, Colorado
• Gives time based on a Cesium atomic clock– result not completely accurate due to network delays
Slide 10©SoftMoore Consulting
By default, the telnet client is not installed on WindowsVista. To install telnet Start → Control Panel → Programs and Features
→ Turn Windows features on or off→ Telnet Client option
The Socket Class
• Hides the complexities of establishing a network connection and sending information across it
• Provides the same programming interface used for working with files
• Primary constructor/methodsSocket(String host, int port)InputStream getInputStream()OutputStream getOutputStream()void close()
Slide 11©SoftMoore Consulting
Streams
• A stream is a sequence of bytes
• I/O from disk, network, memory, etc. is handled in exactly the same way.
• Class InputStreamabstract int read()abstract void close()
• Class OutputStreamabstract void write(int b)abstract void close()
Slide 12©SoftMoore Consulting
Class PrintStream
• Method print() outputs an object, primitive, or string.
• Method println() does the same thing, but it adds a newline at the end.
• Object System.out is a PrintStream.
• ExamplePrintStream ps = new PrintStream(outputstream);
Slide 13©SoftMoore Consulting
Class BufferedReader
• Provides methodString readLine()
• ExamplesInputStreamReader isReader = new InputStreamReader(System.in);BufferedReader reader = new BufferedReader(isReader)
Slide 14©SoftMoore Consulting
Example: Using Sockets
import java.io.*;import java.net.*;
...
Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);InputStream is = s.getInputStream();InputStreamReader isReader = new InputStreamReader(is);BufferedReader in = new BufferedReader(isReader);String line;
while ((line = in.readLine()) != null) System.out.println(line);
in.close();
...
Slide 15©SoftMoore Consulting
Example: Simple Browser Using Sockets
import java.net.*;import java.io.*;
public class SimpleHttpBrowser { public static void main(String[] args) throws Exception { String host = args[0]; int port = Integer.parseInt(args[1]);
Socket s = new Socket(host, port);
InputStream inStream = s.getInputStream(); OutputStream outStream = s.getOutputStream();
Slide 16©SoftMoore Consulting
Example: Simple Browser Using Sockets(continued)
PrintWriter out = new PrintWriter( new OutputStreamWriter(outStream), true);
BufferedReader in = new BufferedReader( new InputStreamReader(inStream));
out.println("GET / HTTP/1.1"); out.println("Host: " + host + ":" + port); out.println();
String line; while ((line = in.readLine()) != null) System.out.println(line);
in.close(); out.close(); } }
Slide 17©SoftMoore Consulting
Client/Server Overview
• Can communicate with remote file systems using a client/server model
• Server listens for connection requests from clients
• Clients know how to connect to the server via a port number
• Upon connection, server processes the request coming across the network from the client
• Connection can remain open or shut down after each transaction
Slide 18©SoftMoore Consulting
Client-Server
• Client – initiates connection– retrieves data– displays data – responds to user input– requests more data
• Examples– web browser– chat program– PC accessing files
• Server – responds to connection– receives data request– looks up data– delivers it
• Examples– web server– database server– email server– domain name server
Slide 19©SoftMoore Consulting
Difference between client and server isrelative – it’s just peers talking to each other.
URL
• Format– protocol://host[:port][/path/][file][#anchor]
• Examples– http://www.softmoore.com– http://www.softmoore.com/Bib-5.2-JavaAdvanced.html– http://java.sun.com/sfaq/index.html– http://java.sun.com/sfaq/– ftp://ftp.cs.rpi.edu/pub/stl/– http://64.233.187.99:80/
(same as http://www.google.com)
Slide 20©SoftMoore Consulting
java.net.URL
• URL(String)– creates a URL object from the String representation
• URL(String, String, int, String)– creates a URL object from the specified protocol, host, port
number, and file
• URL(URL context, String spec)– creates a URL by parsing the specification spec within a
specified context.
• InputStream openStream()– opens a connection to this URL and returns an InputStream
for reading from that connection
Slide 21©SoftMoore Consulting
java.net.URL(continued)
• URLConnection openConnection()– Returns a URLConnection object that represents a connection
to the remote object referred to by the URL.
• MalformedURLException– thrown if you try to create a bogus URL– usually means bad user input, so fail gracefully and informatively
• accessor methods– getProtocol() – getHost()– getPort() – getFile()– getRef()
Slide 22©SoftMoore Consulting
java.net.URLConnection
• InputStream getInputStream()– returns an input stream that reads from this open connection– makes the connection if it has not already been made
• URLConnection creates the socket and handles the protocol (e.g. HTTP) for you
• There are also handlers for other protocols– ftp, gopher, file, mailto, or you can write your own– getOutputStream()
• Handles relative URLs via CodeBase/DocumentBase
Slide 23©SoftMoore Consulting
java.net.URLConnection(continued)
Object getContent()
• Makes the connection if it hasn’t already been made
• Returns an object that’s appropriate for this file’s MIME type
• For text, returns an InputStream
• For images, returns an ImageObserver
• Only supports text/plain, text/Generic, image/gif, and image/jpeg
• You can add your own ContentHandler if you like
Slide 24©SoftMoore Consulting
Example: Simple Browser Using URLs
import java.net.*;import java.io.*;
public class SimpleBrowser { public static void main(String[] args) throws Exception { URL url = new URL(args[0]); InputStream is = url.openStream(); InputStreamReader isReader = new InputStreamReader(is); BufferedReader in = new BufferedReader(isReader); String line;
while ((line = in.readLine()) != null) System.out.println(line);
in.close(); } }
Slide 25©SoftMoore Consulting
java.net.HttpURLConnection
• Extends URLConnection with additional support for HTTP connections.
• Usage: Cast a URLConnectionURL url = new URL("http://www.android.com/");HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
• Selected methods in HttpURLConnection– int getResponseCode() – String getResponseMessage() – String getHeaderField(int n)– String getHeaderFieldKey(int n)
Slide 26©SoftMoore Consulting
©SoftMoore Consulting Slide 27
Networking Application: Checking URLs
URLConnection conn = url.openConnection();
if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn;
// response code 400 or higher is bad if (httpConn.getResponseCode() >= 400) printBadUrl(url, httpConn.getResponseCode(), httpConn.getResponseMessage()); }else printFeedback("Skipping " + url + ": not HTTP protocol");
java.net.URLEncoder
static String encode(String)
• The ASCII characters ‘a’ through ‘z’, ‘A’ through ‘Z’, and ‘0’ through ‘9’ remain the same.
• The space character is converted into a plus sign ‘+’.
• All other characters are converted into the 3-character string “%xy”, where xy is the two-digit hexadecimal representation of the lower 8-bits of the character.
Slide 28©SoftMoore Consulting