CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.

Slides:



Advertisements
Similar presentations
CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Advertisements

Networking with Java 1. Introduction to Networking 2.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
Java Sockets Source:
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
1 Java Networking CS , Spring 2008/9. 2 Today’s Menu Networking Basics  TCP, UDP, Ports, DNS, Client-Server Model TCP/IP in Java Sockets URL 
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Networking with Java 1: The Client Side. Introduction to Networking.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
13-Jul-15 Sockets and URLs. 2 Sockets A socket is a low-level software device for connecting two computers together Sockets can also be used to connect.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
1 Networking with Java. 2 Introduction to Networking.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
SOCKET PROGRAMMING. Client/Server Communication At a basic level, network-based systems consist of a server, client, and a media for communication as.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CSE 143 Lecture 21 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp
Appendix F: Network Programming in Java ©SoftMoore ConsultingSlide 1.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
Distributed Java Notes Dr. Raed Alqadi 1. TCP for Client/Server Client "knows" a particular type of service that exists at given address and port - E.g.,
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
© 1997 Elliotte Rusty Harold10/7/2015 URLs, InetAddresses, and URLConnections High Level Network Programming Elliotte Rusty Harold
Import java.net.*; import java.io.*; public class LowPortScanner { public static void main(String[] args) { String host = "localhost"; if (args.length.
DBI Representation and Management of Data on the Internet.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
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.
NETWORK PROGRAMMING.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 15 IO Using http Rob Pooley
Networking Java (2/3)
Servers and Sockets Carol Wolf Computer Science. Java network programming classes  SocketImpl – abstract class and superclass of the rest  Four fields:
Java IO. Why IO ? Without I/O, your program is a closed box. Without I/O, your program is a closed box. I/O gives your Java program access to your hard.
MIDP Programming Networking. Chapter Objectives The CLDC Streams Model Generic Connection Framework (GCF) Supported Protocols Creating a Connection Review.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
URL Programming Mimi Opkins CECS277. What is a URL?  URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Building Java Programs Bonus Slides I/O Streams; Exceptions; Inheritance Copyright (c) Pearson All rights reserved.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
자바네트워크 제 13 주 URLConnection 클래스 IP 멀티캐스팅 소켓. 여러분들의 질문 지난 주 실습 내용 질문.
Network Programming Communication between processes Many approaches:
Java.net CS-328 Dick Steflik.
Source: Java Sockets Source:
Network Programming Introduction
Networking with Java 2.
Network Programming Introduction
Network Programming Introduction
Sockets and URLs 17-Sep-18.
Sockets and URLs 13-Nov-18.
Clients and Servers 19-Nov-18.
URL in Java C343 Lab (Week 13).
Clients and Servers 1-Dec-18.
Networking.
Sockets and URLs 3-Dec-18.
CSE 143 Lecture 25 I/O Streams; Exceptions; Inheritance read 9.3, 6.4
Uniform Resource Locator: URL
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Presentation transcript:

CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina

4/1/20042 URL Classes A framework for easily accessing and decoding URL resources Enable an application to create URL object using standard URL addressing scheme Then call getContent() method to download and decode the addressed object Two chains of control Protocol chain Content chain

4/1/20043 URL Chains of Control URL URLStreamHandler URLConnection URLStreamHandlerFactory HTTP / FTP / … URLConnection ContentHandler ContentHandlerFactory gif / au / … Protocol chainContent chain

4/1/20044 Class URL Constructors URL(String url) throws MalformedURLException URL(String protocol, String host, String file) throws MalformedURLException URL(String protocol, String host, int port, String file) throws MalformedURLException URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException URL(URL context, String spec) throws MalformedURLException URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException

4/1/20045 Class URL Methods String getProtocol() String getHost() int getPort() String getFile() String getRef() boolean sameFile(URL other) String toExternalForm() URLConnection openConnection() throws IOException InputStream openStream() throws IOException Object getContent() throws IOException protected void set(String protocol, String host, int port, String file, String ref) static void setURLStreamHandlerFactory(URLStreamHandlerFactory factory)

4/1/20046 Class URL Exceptions IOException MalformedURLException

4/1/20047 Example of Using URL Class URL url = new URL ( InputStream in = url.openStream (); Reader reader = new InputStreamReader (in, “latin1”); BufferedReader bufferedReader = new BufferedReader (reader); PrintWriter console = new PrintWriter (System.out); String line; while ((line = bufferedReader.readLine ())_ != null) console.println (line); console.flush(); bufferedReader.close ();

4/1/20048 Class URLConnection Constructor protected URLConnection(URL url)

4/1/20049 Class URLConnection Methods URL getURL() void setDoInput(boolean doInput) boolean getDoInput() void setDoOutput(boolean doOutput) boolean getDoOutput() void setAllowUserInteraction(boolean allow) boolean getAllowUserInteraction() void setUseCaches(boolean use) boolean getUseCaches() void setRequestProperty(String key, String value) String getRequestProperty(String key) void setIfModifiedSince(long ifModified) long getIfModifiedSince() abstract void connect() throws IOException

4/1/ Class URLConnection Methods OutputStream getOutputStream() throws IOException InputStream getInputStream() throws IOException Object getContent() throws IOException String getHeaderField(String name) String getHeaderFieldKey(int n) String getHeaderField(int n) int getHeaderFieldInt(String name, int alt) long getHeaderFieldDate(String name, long alt) int getContentLength() String getContentType() String getContentEncoding() long getExpiration() long getDate() long getLastModified()

4/1/ Class URLConnection Static methods void setDefaultAllowUserInteraction(boolean defaultAllow) boolean getDefaultAllowUserInteraction() void setDefaultRequestProperty(String key, String value) String getDefaultRequestProperty(String key) protected String guessContentTypeFromName(String fname) String guessContentTypeFromStream(InputStream is) FileNameMap getFileNameMap() void setFileNameMap(FileNameMap map) void setContentHandlerFactory(ContentHandlerFactory factory)

4/1/ Class URLConnection Variables protected URL url protected boolean doInput protected boolean doOutput protected boolean allowUserInteraction protected boolean useCaches protected long ifModifiedSince protected boolean connected Exceptions IOException

4/1/ Example of Using URLConnection Class // String user, password; URL url = new URL (getCodeBase (), “/cgi-bin/update.cgi”); URLConnection connection = url.openConnection (); connection.setDoOutput (true); OutputStream out = connection.getOutputStream (); Writer writer = new OutputStreamWriter (out, “latin1”); writer.write (“user=” + URLEncoder.encode (user)); writer.write (“&password=” + URLEncoder.encode (password)); writer.close (); InputStream in = connection.getInputStream (); Reader reader = new InputStreamReader (in, “latin1”); BufferedReader bufferedReader = new BufferedReader (reader); PrintWriter console = new PrintWriter (System.out); String line; while ((line = bufferedReader.readLine ())_ != null) console.println (line); console.flush(); bufferedReader.close ();

4/1/ Class HttpURLConnection Constructor protected HttpURLConnection(URL url)

4/1/ Class HttpURLConnection Methods void setRequestMethod(string method) throws ProtocolException String getRequestMethod() int getResponseCode() throws IOException String getResponseMessage() throws IOException abstract void disconnect() boolean abstract usingProxy()

4/1/ Class HttpURLConnection Static methods void setFollowRedirects(boolean set) boolean getFollowRedirects()

4/1/ Class HttpURLConnection Variables protected String method protected int responseCode protected String responseMessage Static variables Success codes Redirect codes Client error codes Server error codes

4/1/ Example of HttpURLConnection Class URL url = new URL (getCodeBase (), “/cgi-bin/update.cgi”); URLConnection conn = url.openConnection (); HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode (); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConn.getInputStream (); Reader reader = new InputStreamReader (in, “latin1”); BufferedReader bufferedReader = new BufferedReader (reader); PrintWriter console = new PrintWriter (System.out); String line; while ((line = bufferedReader.readLine ())_ != null) console.println (line); console.flush(); bufferedReader.close (); }

4/1/ Interface URLStreamHandlerFactory Method URLStreamHandler createURLStreamHandler(String protocol)

4/1/ Class URLStreamHandler Create an appropriate instance of URLConnection class capable of serving a particular protocol Method protected abstract URLConnection openConnection(URL url) throws IOException protected void parseURL(URL url, String spec, int start, int limit) protected String toExternalForm(URL url) protected void setURL(URL url, String protocol, String host, int port, String file, String ref)

4/1/ Interface ContentHandlerFactory Method ContentHandler createContentHandler(String mimetype)

4/1/ Class ContentHandler Decode content of a URL and produce result that is usable by Java run time Method abstract Object getContent(URLConnection connection) throws IOException

4/1/ An HTTP Protocol Handler Example Examine headers sent by server to determine type of file and to invoke appropriate handler URL getContent() HTTPURLStreamHandler openConnection() HTTPURLConnection getInputStream() URLStreamHandlerFactoryImpl createURLStreamHandler() URLConnection getContent() TextPlainContentHandler getContent() ContentHandlerFactoryImpl createContentHandler() PageViewer main()

4/1/ Class URLStreamHandlerFactoryImpl /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN X * * * * Copyright (c) Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; public class URLStreamHandlerFactoryImpl implements URLStreamHandlerFactory { public URLStreamHandler createURLStreamHandler (String protocol) { if (protocol.equalsIgnoreCase ("http")) return new HTTPURLStreamHandler (); else if (protocol.equalsIgnoreCase ("finger")) return new FingerURLStreamHandler (); else if (protocol.equalsIgnoreCase ("rawfinger")) return new RawFingerURLStreamHandler (); else return null; }

4/1/ Class HTTPURLStreamHandler /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN X * * * * Copyright (c) Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; public class HTTPURLStreamHandler extends URLStreamHandler { protected URLConnection openConnection (URL url) throws IOException { return new HTTPURLConnection (url); }

4/1/ Class HTTPURLConnection /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN X * * * * Copyright (c) Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; import java.util.*; Import java.text.*; public class HTTPURLConnection extends URLConnection { // public HTTPURLConnection (URL url) … // public void setRequestProperty (String name, String value) … // public String getRequestProperty (String name) … // public synchronized void connect () throws IOException … // public InputStream getInputStream () throws IOException … // public String getHeaderFieldKey (int index) … // public String getHeaderField (int index) … // public String getHeaderField (String key) … }

4/1/ Constructor HTTPURLConnection protected Hashtable requestProperties; protected Vector keys; protected Hashtable headers; public HTTPURLConnection (URL url) { super (url); requestProperties = new Hashtable (); keys = new Vector (); headers = new Hashtable (); }

4/1/ Method setRequestProperty public void setRequestProperty (String name, String value) { if (connected) throw new IllegalStateException ("Already connected."); requestProperties.put (name, value); } public String getRequestProperty (String name) { return (String) requestProperties.get (name); }

4/1/ Method connect protected InputStream in; public synchronized void connect () throws IOException { if (!connected) { String host = url.getHost (); int port = (url.getPort () == -1) ? 80 : url.getPort (); Socket socket = new Socket (host, port); sendRequest (socket.getOutputStream ()); in = new BufferedInputStream (socket.getInputStream ()); readHeaders (); connected = true; } // protected void sendRequest (OutputStream out) throws IOException … // protected void readHeaders () throws IOException …

4/1/ Method sendRequest protected void sendRequest (OutputStream out) throws IOException { setRequestProperty ("User-Agent", "JNP-HTTP/2e"); if (ifModifiedSince != 0) { Date since = new Date (ifModifiedSince); SimpleDateFormat formatter = new SimpleDateFormat ("EEE, d MMM yyyy hh:mm:ss z"); formatter.setTimeZone (TimeZone.getTimeZone ("GMT")); setRequestProperty ("If-Modified-Since", formatter.format (since)); } StringBuffer request = new StringBuffer ("GET "); request.append (URLEncoder.encode (url.getFile ())); request.append (" HTTP/1.0\r\n"); Enumeration keys = requestProperties.keys (); while (keys.hasMoreElements ()) { String key = (String) keys.nextElement (); request.append (key); request.append (": "); request.append (requestProperties.get (key)); request.append ("\r\n"); } request.append ('\n'); out.write (request.toString ().getBytes ("latin1")); }

4/1/ Method readHeaders protected void readHeaders () throws IOException { String status = readLine (); String header; while (((header = readLine ()) != null) && (!header.trim ().equals (""))) { int colon = header.indexOf (":"); if (colon >= 0) { String key = header.substring (0, colon).trim (); String value = header.substring (colon + 1).trim (); keys.addElement (key); headers.put (key.toLowerCase (), value); } // protected String readLine () throws IOException …

4/1/ Method readLine protected String readLine () throws IOException { StringBuffer result = new StringBuffer (); int chr; while (((chr = in.read ()) != -1) && (chr != 10) && (chr != 13)) result.append ((char) chr); if ((chr == -1) && (result.length () == 0)) return null; if (chr == 13) { in.mark (1); if (in.read () != 10) in.reset (); } return result.toString (); }

4/1/ Method getInputStream public InputStream getInputStream () throws IOException { if (!doInput) throw new IllegalStateException ("Input disabled."); connect (); return in; }

4/1/ Methods to Read Headers public String getHeaderFieldKey (int index) { if (!connected) throw new IllegalStateException ("Not connected."); if (index < keys.size ()) return (String) keys.elementAt (index); else return null; } public String getHeaderField (int index) { if (!connected) throw new IllegalStateException ("Not connected."); if (index < keys.size ()) return getHeaderField ((String) keys.elementAt (index)); else return null; } public String getHeaderField (String key) { if (!connected) throw new IllegalStateException ("Not connected."); return (String) headers.get (key.toLowerCase ()); }

4/1/ Class ContentHandlerFactoryImpl /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN X * * * * Copyright (c) Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; public class ContentHandlerFactoryImpl implements ContentHandlerFactory { public ContentHandler createContentHandler (String mimeType) { if (mimeType.equalsIgnoreCase ("text/plain")) return new TextPlainContentHandler (); else return null; }

4/1/ Class TextPlainContentHandler /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN X * * * * Copyright (c) Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; public class TextPlainContentHandler extends ContentHandler { public Object getContent (URLConnection connection) throws IOException { InputStream in = connection.getInputStream (); Reader reader = new InputStreamReader (in, "latin1"); BufferedReader bufferedReader = new BufferedReader (reader); StringBuffer content = new StringBuffer (); String line; while ((line = bufferedReader.readLine ()) != null) content.append (line).append ('\n'); bufferedReader.close (); return content.toString (); }

4/1/ Class PageViewer /* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN X * * * * Copyright (c) Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */ import java.io.*; import java.net.*; public class PageViewer { public static void main (String args[]) throws IOException { if (args.length != 1) throw new IllegalArgumentException ("Usage: PageViewer "); URL.setURLStreamHandlerFactory (new URLStreamHandlerFactoryImpl ()); URLConnection.setContentHandlerFactory (new ContentHandlerFactoryImpl ()); URL url = new URL (args[0]); System.out.println (url.getContent ()); }

4/1/ Next Class Remote method invocation (RMI) Read JNP Ch. 23