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.
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);
•
• 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();
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 {
Socket s = new Socket("www.cs.cityu.edu.hk", 80);
DataInputStream in = new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
out.println("GET / HTTP/1.0");
out.println();
String line;
while ((line=in.readLine())!=null)
System.out.println("> "+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/
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
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.2 Example
import java.net.*;
import java.io.*;
class HttpClient1 {
public static void main(String[] args ) {
try {
Socket s = new Socket("www.cs.cityu.edu.hk", 80);
DataInputStream in = new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
out.println("HEAD /index.html HTTP/1.0");
out.println();
String line;
while ((line=in.readLine())!=null)
System.out.println("> "+line);
s.close();
} catch (Exception e) { System.out.println(e);}
}
}
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)
–and much more...
• A simple HTML file
A HTML to test applet
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 within a specified context.
Excetption
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()
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()
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
("URL: " + url.toExternalForm() + "\n" +
" File: " + url.getFile() + "\n" +
" Host: " + url.getHost() + "\n" +
" Port: " + url.getPort() + "\n" +
" Protocol: " + url.getProtocol() + "\n" +
" Reference: " + url.getRef());
} catch(MalformedURLException mue) {
System.out.println("Bad URL.");
}
} else
System.out.println("Usage: UrlTest
}
}
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]+"is an invalid URL:"+mue);
} catch(IOException ioe) {
System.out.println("IOException: "+ioe);
}
}
private static void checkUsage(String[] args) {
if (args.length!=1) {
System.out.println("Usage: UrlRetriever2
System.exit(-1);
}
}
}
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.
Tidak ada komentar:
Posting Komentar