Your SlideShare is downloading. ×
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
T2
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

T2

718

Published on

Java network programing.

Java network programing.

Published in: Education, Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
718
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
11
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Tutorial 2 Network Programming in Java Tutorial 2 Network Programming in Java Objectives Java network programming introduction HTTP introduction Java URL class for establishing HTTP connection 1
  • 2. Tutorial 2 Network Programming in Java 1 Java network programming introduction Java provides java.net package to support network programming. 1.1 Client and Server  A client obtains a service via sending a request to a server  A client initiates a connection, retrieves data, responds user input. For example, web browser, chat program (ICQ)  A server provides a set of services, such as web server, time server, file server, chat server.  A server responds to connection, receives requests for data from client, and delivers it to client.  The protocol between client and server is the communication rule, for example FTP, SMTP, and HTTP. 2
  • 3. Tutorial 2 Network Programming in Java 1.2 Socket  We use socket to establish the connection between client and server.  Socket identifies a connection using host address and port number.  A socket is a bi-directional communication channel  Java differentiates client sockets from server sockets. e.g. for client Socket client=new Socket(“hostname”,portNumber); for server ServerSocket server=new SeverSocket(portNumber);  Client port 13 Time Service port 80 Web Service Socket Socket Server 3
  • 4. Tutorial 2 Network Programming in Java  Well known ports for server 80 web server 21 Ftp server 13 Time server 23 Telnet 25 Email(SMTP) 1.3 The connection between server and client using socket Socket Operations at Client Side  create a client socket: Socket (host, port) s = new Socket (“java.sun.com”, 13)  get input / output data streams out of the socket: in = new DataInputStream(s.getInputStream ()); out = new DataOutputStream( s.getOutputStream()); out = new PrintStream( s.getOutputStream());  read from input / write to output data streams: String str = in.readLine(); out.println ( “Echo:” + str + “r”);  close the socket: s.close(); 4
  • 5. Tutorial 2 Network Programming in Java Socket Operations at Server Side A server is always waiting for being connected. It need not initiate a connection to a host. So a server socket need only specify its own port no.  create a server socket: ServerSocket (port) ServerSocket s = new ServerSocket(8189);  accept an incoming connection: Socket snew = s.accept ();  get input / output data streams out of the socket for the incoming client: in = new DataInputStream(snew.getInputStream()); out = new PrintStream(snew.getOutputStream());  close the socket for the incoming client: snew.close(); 1.4 Example : A web Client import java.net.*; import java.io.*; class HttpClient { public static void main(String[] args ) { try { Tutorial for CS5286 Algorithms&Tech for Web Search 5
  • 6. Tutorial 2 Network Programming in Java Socket s = new Socket(quot;www.cs.cityu.edu.hkquot;,80); DataInputStrea in = new m DataInputStream(s.getInputStream()); PrintStream out=new PrintStream(s.getOutputStream()); out.println(quot;GET / HTTP/1.0quot;); out.println(); String line; while ((line=in.readLine())!=null) System.out.println(quot;> quot;+line); s.close(); } catch (Exception e) { System.out.println(e);} } } 2 HTTP introduction HTTP( Hypertext Transfer Protocol) is an application layer protocol , just like FTP, SMTP, etc. The WWW is based on HTTP, for the communication rule between the browser and web server is HTTP. You can check following URL for detailed document about HTTP . http://www.w3.org/Protocols/ Tutorial for CS5286 Algorithms&Tech for Web Search 6
  • 7. Tutorial 2 Network Programming in Java 2.1 Overview HTTP request Format: Method URI HTTP Version For example: GET / HTTP/1.0 There are three most important methods in HTTP 1.0 , include GET, PUT and HEAD  To request a web page, a browser sends a web server an HTTP GET message  To send data to a web server, a browser can use an HTTP POST message  To get information about document size , modification date, but not document itself , you can use HTTP HEAD request. And there are some other HTTP methods added in HTTP 1.1 , such as PUT, DELETE, OPTIONS, and TRACE. Also client can send additional information about itself to web server, such as browser type, operation system. HTTP response Tutorial for CS5286 Algorithms&Tech for Web Search 7
  • 8. Tutorial 2 Network Programming in Java After receiving client’s request, web server will respond. It includes web server HTTP version, HTTP server status code for client’s request, and some information about document, such as Content-Length, Content-Type, Last-Modified date. 2. browser sends 3. server fetches web 1. user types or GET URL to page for URL clicks URL server 4. server sends web page data to browser 5. browser displays web page* internet Tutorial for CS5286 Algorithms&Tech for Web Search 8
  • 9. Tutorial 2 Network Programming in Java 2.2 Example import java.net.*; import java.io.*; class HttpClient1 { public static void main(String[] args ) { try { Socket s = new Socket(quot;www.cs.cityu.edu.hkquot;, 80); DataInputStream in = new DataInputStream(s.getInputStream()); PrintStream out=new PrintStream(s.getOutputStream()); out.println(quot;HEAD /index.html HTTP/1.0quot;); out.println(); String line; while ((line=in.readLine())!=null) System.out.println(quot;> quot;+line); s.close(); } catch (Exception e) { System.out.println(e);} } } Tutorial for CS5286 Algorithms&Tech for Web Search 9
  • 10. Tutorial 2 Network Programming in Java 2.3 URL: Uniform Resource Locator  The URL standard defines a common way to refer to any web page, anywhere on the web  format: protocol://web_server_name/page_name example: http://www.yahoo.com/index.html  URLs are most commonly used in conjunction with the HTTP protocol to GET a URL, or POST data to a URL  a URL can refer to many kinds of web page: plain text, formatted text (usually in HTML…), multimedia, database, ... 2.4 HTML: HypeText Markup Language •Specific mark-up language used in the Web •Many kinds of markups –low-level appearance (font changes, lists) –logical structure (title, headings) –links to other documents –embedded graphics –meta-information (language) Tutorial for CS5286 Algorithms&Tech for Web Search 10
  • 11. Tutorial 2 Network Programming in Java –and much more...  A simple HTML file <HTML> <HEAD> <TITLE> A HTML to test applet </TITLE> </HEAD> <BODY> <applet code=quot;HelloKitty2.classquot; Width=quot;80quot; Height=quot;100quot;> </applet> </BODY> </HTML> Tutorial for CS5286 Algorithms&Tech for Web Search 11
  • 12. Tutorial 2 Network Programming in Java 3 Java URL class Java provides URL class to make it much easier to deal with HTTP connection. We don’t need to care about low layer socket connection. You can find detailed information about them on following URL, http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html 3.1 URL Constructor 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, int port, String file, URLStreamHandler handler) Creates a URL object from the specified protocol, host, port number, file, and handler. URL(String protocol, String host, String file) Creates a URL from the specified protocol name, host name, and file name. URL(URL context, String spec) Creates a URL by parsing the given spec within a specified context. URL(URL context, String spec, URLStreamHandler handler) Creates a URL by parsing the given spec with the specified handler wit in a specified h context. Excetption MalformedURLException Thrown if you try to create a bogus URL Usually means bad user input, so fail gracefully and informatively Tutorial for CS5286 Algorithms&Tech for Web Search 12
  • 13. Tutorial 2 Network Programming in Java accessor methods getProtocol(), getHost(), getPort(), getFile(), getRef() openConnection() public URLConnection openConnection() throws IOException Returns a URLConnection object that represents a connection to the remote object referred to by the URL. If there is not already an open connection, the connection is opened by calling the openConnection method of the protocol handler for this URL. OpenStream() public final InputStream openStream() throws IOException Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for: openConnection().getInputStream() getContent public final Object getContent() throws IOException Returns the contents of this URL. This method is a shorthand for: openConnection().getContent() Tutorial for CS5286 Algorithms&Tech for Web Search 13
  • 14. Tutorial 2 Network Programming in Java Example 1 import java.net.*; public class UrlTest { public static void main(String[] args) { if (args.length == 1) { try { URL url = new URL(args[0]); System.out.println (quot;URL: quot; + url.toExternalForm() + quot;nquot; + quot; File: quot; + url.getFile() + quot;nquot; + quot; Host: quot; + url.getHost() + quot;nquot; + quot; Port: quot; + url.getPort() + quot;nquot; + quot; Protocol: quot; + url.getProtocol() + quot;nquot; + quot; Reference: quot; + url.getRef()); } catch(MalformedURLException mue) { System.out.println(quot;Bad URL.quot;); } } else System.out.println(quot;Usage: UrlTest <URL>quot;); } } Tutorial for CS5286 Algorithms&Tech for Web Search 14
  • 15. Tutorial 2 Network Programming in Java Example 2 was given in Tutorial 1. Using openStream() Example 3 Using getContent() import java.net.*; import java.io.*; public class UrlRetriever1 { public static void main(String[] args) { checkUsage(args); try { URL url=new URL(args[0]); DataInputStream in= new DataInputStream((InputStream)url.getContent()); String line; while ((line=in.readLine())!=null) System.out.println(line); in.close(); } catch(MalformedURLException mue) { System.out.println(args[0]+quot;is an invalid URL:quot;+mue); } catch(IOException ioe) { System.out.println(quot;IOException: quot;+ioe); } } private static void checkUsage(String[] args) { if (args.length!=1) { System.out.println(quot;Usage: UrlRetriever2 <URL>quot;); System.exit(-1); } } } Tutorial for CS5286 Algorithms&Tech for Web Search 15
  • 16. Tutorial 2 Network Programming in Java 4 Exercises  Implement a HTTP server (Simulated) using ServerSocket.  Using URL Class, write a http client to retrieve http://www.cs.cityu.edu.hk/index.html, and return the last modified date, Content-Length, Content-Type of this web page. Tutorial for CS5286 Algorithms&Tech for Web Search 16

×